Django更新用户配置文件

时间:2015-11-30 02:46:59

标签: python django

我将用户档案更新为客户时面临很多问题。

问题:

  • 没有错误显示
  • 只有电子邮件,地址和生日正在更新
  • 想要更新用户中的名字和姓氏

如果此类更新配置文件有任何简短的方法,请告诉我或尝试帮助您使用此代码。谢谢。

models.py

from django.db import models
from django.contrib.auth.models import User


class SignupUser(models.Model):
    user = models.OneToOneField(User)
    address = models.CharField(blank=False, max_length=200)
    birthday = models.DateTimeField('Birthday')

    def __str__(self):
        return self.address


User.profile = property(lambda u: SignupUser.objects.get_or_create(user=u)[0])

forms.py

from django import forms
from django.contrib.auth.models import User
from signup.models import SignupUser

class UpdateProfile(forms.ModelForm):
    class Meta:
        model = SignupUser
        fields = ['address', 'birthday']


class UpdateUser(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']


    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('This is not your email')

        return email

views.py

def editprofile(request):
    if request.method == 'POST':
        profileup = UpdateProfile(request.POST or None, instance=request.user.profile)
        if profileup.is_valid():
            profileup.save()
            userup = UpdateUser(request.POST or None, instance=request.user)
            if userup.is_valid():
                user = userup.save(commit=False)
                user.first_name == request.POST['first_name']
                user.save()
            return HttpResponseRedirect('/authority/editprofile/')
    else:
        user = request.user
        profile = user.profile
        userup = UpdateUser(instance=user)
        profileup = UpdateProfile(instance=profile)

    args = {
        'userup': userup,
        'profileup': profileup, 
    }
    return render(request, 'auth/editprofile.html', args)

1 个答案:

答案 0 :(得分:0)

如果userup.is_valid()之后尝试添加else子句以获取错误的更多信息。 但我建议你使用基于类的视图UpdateView