简体   繁体   中英

How to create sign up form for customer user model in Django?

I have extended the User Model provided by Django into Owner object. What I intend to do, is create a sign up form which creates a new user in my application and also fill up the custom fields defined in Owner object. My code is as follows -

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()

SO basically, Owner model extends the User model via One-to-One relationship method. And there is a signal receiver method which creates the Owner object when User object is created.

Forms.py -

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

The form basically contains the fields that I want to extend the User model with.

And the 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})

The above code uses this as reference. The above code basically creates a UserCreationForm provided by Django which is used to create the user and once the user is saved to db, the Owner object is created on it. However, when I click on submit, error occurs.

  1. When form is submitted - below is the form rendered by Django

形成

Upon submission , I receive the following error -

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

The contact field in the model should probably be a

Not requiring an input: contact = models.CharField(max_length=10, null = True, blank = True)

Requiring an input: contact = models.CharField(max_length=10)

If you use an IntegerField for the phone number, usually people will type in '-' or '.' between the sets of numbers (123-123-1234), this will result in an error.

But if you want to keep it as an Integer it would be: contact = models.IntegerField()

Django docs for it are here https://docs.djangoproject.com/en/2.2/topics/db/models/#fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM