如何在Django中为客户用户模型创建注册表单?

时间:2019-06-20 05:53:36

标签: python django authentication django-models django-forms

我已经将Django提供的用户模型扩展到Owner对象中。我打算做的是创建一个注册表单,该表单将在我的应用程序中创建一个新用户,并填写Owner对象中定义的自定义字段。我的代码如下-

model.py-

class Owner(BaseModel):

    id = models.AutoField(primary_key=True)
    gym = models.ForeignKey(Gym, on_delete = models.CASCADE)
    # User model
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    address = models.OneToOneField('Address', on_delete=models.CASCADE)

    contact =  models.BigIntegerField(null=False)
    dob = models.DateTimeField(null=True)
    gender =  models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, default=None)

    profile_photo = models.ImageField( upload_to='static/images/gym_owner/profile', null=True, blank=True)

    def __str__(self):
        return f'{self.user.first_name} {self.user.last_name}'


    class Meta:
        verbose_name_plural = "Owner"


@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Owner.objects.create(user=instance)
    instance.owner.save()

因此,基本上,Owner模型通过User关系方法扩展了One-to-One模型。还有一个信号接收器方法,当创建User对象时会创建Owner对象。

Forms.py-

class OwnerForm(ModelForm):
    class Meta:
        model = Owner
        fields = ('gym', 'address', 'contact', 'gender',  'profile_photo')

该表单基本上包含我要用于扩展User模型的字段。

还有view.py-

@transaction.atomic
def owner_signup(request):
    if request.user.is_authenticated:
        return redirect('dashboard')
    if request.method == 'GET':
        userForm = UserCreationForm()
        ownerForm = OwnerForm()
        return render(request, 'gym_owner/signup.html', {'userform': userForm, 'ownerForm': ownerForm})
    if request.method == 'POST':
        userForm = UserCreationForm(request.POST)
        ownerForm = OwnerForm(request.POST)

        if userForm.is_valid() and ownerForm.is_valid():
            user = userForm.save()
            user.refresh_from_db()
            ownerForm = OwnerForm.save(request.POST, instance=user.owner)
            ownerForm.full_clean()
            ownerForm.save()
            #form.save()
            username = userForm.cleaned_data.get('username')
            password = userForm.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return render(request, 'gym_owner/dashboard.html')
        else:
            # If there were errors, we render the form with these
            # errors
            return render(request, 'gym_owner/signup.html', {'userform': userForm, 'ownerForm': ownerForm})

以上代码使用this作为参考。 上面的代码基本上创建了UserCreationForm提供的Django,该IntegrityError at /owner/signup NOT NULL constraint failed: gym_owner_owner.contact Request Method: POST Request URL: http://localhost:8000/owner/signup Django Version: 2.2.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: gym_owner_owner.contact Exception Location: C:\Users\Dev\Desktop\Django-Test\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users\Dev\Desktop\Django-Test\venv\Scripts\python.exe Python Version: 3.6.6 Python Path: ['C:\\Users\\Dev\\Desktop\\Django-Test\\gym', 'C:\\Users\\Dev\\Desktop\\Django-Test\\venv\\Scripts\\python36.zip', 'C:\\Users\\Dev\\Desktop\\Django-Test\\venv\\DLLs', 'C:\\Users\\Dev\\Desktop\\Django-Test\\venv\\lib', 'C:\\Users\\Dev\\Desktop\\Django-Test\\venv\\Scripts', 'c:\\users\\Dev\\appdata\\local\\programs\\python\\python36-32\\Lib', 'c:\\users\\Dev\\appdata\\local\\programs\\python\\python36-32\\DLLs', 'C:\\Users\\Dev\\Desktop\\Django-Test\\venv', 'C:\\Users\\Dev\\Desktop\\Django-Test\\venv\\lib\\site-packages'] Server time: Thu, 20 Jun 2019 05:49:02 +0000 用于创建用户,并且将用户保存到db后,便在其上创建了Owner对象。但是,当我单击提交时,会发生错误。

  1. 提交表单时-以下是Django呈现的表单

Form

提交后,我收到以下错误-

{{1}}

1 个答案:

答案 0 :(得分:0)

模型中的联系人字段应该为

不需要输入: 联系人=模型。CharField(max_length = 10,null = True,空白= True)

要求输入: 联系人= models.CharField(max_length = 10)

如果您使用IntegerField作为电话号码,通常人们会输入“-”或“。”。在一组数字(123-123-1234)之间,这将导致错误。

但是,如果您想将其保留为整数,则应为: contact = models.IntegerField()

针对它的Django文档在https://docs.djangoproject.com/en/2.2/topics/db/models/#fields