Django:为用户个人资料添加生日

时间:2018-06-03 19:57:37

标签: django registration profile

我是Django的新手。我一直在为我的问题寻找解决方案,但我找不到任何解决问题的方法。

我有一个新用户的注册视图。在这里,新用户输入他的电子邮件地址和密码(每两次),他的第一个和他的姓氏以及他的生日。一切正常(它保存了电子邮件地址,密码和名称),但我无法用这个表格保存他的生日。 我可以在登录/ admin时添加日期,并保存日期。

感谢您的帮助!

forms.py:

class UserRegisterForm(forms.ModelForm): 
    username=forms.EmailField(label='Email address')
    email=forms.EmailField(label='Confirm Email')
    password=forms.CharField(widget=forms.PasswordInput)
    password2=forms.CharField(widget=forms.PasswordInput)
    first_name=forms.CharField(label='First Name')
    last_name=forms.CharField(label='Last Name')
    birthday=forms.DateField(label='Birthday')
    class Meta:
        model=User
        fields=[
           'username',
           'email',
           'password',
           'password2',
           'first_name',
           'last_name',
           'birthday',
        ]
    def clean(self,*args,**kwargs):
        username=self.cleaned_data.get("username")
        email=self.cleaned_data.get("email")
        password=self.cleaned_data.get("password")
        password2=self.cleaned_data.get("password2")
        username=self.cleaned_data.get("username")
        birthday=self.cleaned_data.get("birthday")
        if username!=email:
            raise forms.ValidationError("Emails must match")
        email_qs=User.objects.filter(username=username)
        if email_qs.exists():
            raise forms.ValidationError("This Email has already been registered")
        if password!=password2:
            raise forms.ValidationError("Passwords must match")
        return super(UserRegisterForm,self).clean(*args,**kwargs)

models.py:

 class UserTest(models.Model):
      username=models.OneToOneField(User, on_delete=models.CASCADE)
      email=models.EmailField(User)
      first_name=models.CharField(max_length=20)
      last_name=models.CharField(max_length=20)
      birthday=models.DateField(auto_now=False, null=True, blank=True)

      def __str__(self):
          return self.username.username

 def create_profile(sender, **kwargs):
     if kwargs['created']:
         user_profile=UserTest.objects.create(username=kwargs['instance'])

 post_save.connect(create_profile,sender=User)

views.py

def register_user_view(request):
    title="Register User"
    form=UserRegisterForm(request.POST or None)
    if form.is_valid():
        user=form.save(commit=False)
        password=form.cleaned_data.get('password')
        birthday=form.cleaned_data.get('birthday')
        user.save(password)
        user.set_password(password)
        user.save()
        new_user=authenticate(username=user.username,password=password)
        login(request,user)
        return redirect("/register/done")
    context={
        "form":form,
        "title":title
    }
    return render(request,"form.html",context)

我到底在哪里输入更多东西(什么?)?

0 个答案:

没有答案