django修改个人资料
model.py
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
date_of_birth = models.DateField(blank=True, null=True, verbose_name='出生日期')
photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True, verbose_name='头像')
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
views.py
from django.contrib.auth.forms import UserChangeForm
from account.models import Profile
#继承django.contrib.auth.forms的UserChangeForm
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = User
fields = ['email',]
field_classes = {'username': UsernameField}
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('date_of_birth', 'photo')
class Edit(View):
def get(self, request):
user_form = CustomUserChangeForm(instance=request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
return render(request,'registration/edit.html',{'user_form':user_form,'profile_form':profile_form})
def post(self, request):
user_form = CustomUserChangeForm(instance=request.user, data=request.POST)
profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
return render(request, 'registration/edit.html', {'user_form': user_form, 'profile_form': profile_form})