Creating a Django Registration Form by Extending Django-Registation Application

纵然是瞬间 提交于 2019-12-03 17:15:08

You are aware that the User model already has first_name and last_name fields, right? Also, you misstyped last_name to last_field.

I would advise to extend the form provided by django-registration and making a new form that adds your new fields. You can also save the first name and last name directly to the User model.

#get the form from django-registration
from registration.forms import RegistrationForm

class MyRegistrationForm(RegistrationForm):
    first_name = models.CharField(max_length = 50, label=u'First Name')    
    last_field = models.CharField(max_length = 50, label=u'Last Name')
    ...
    pincode = models.CharField(max_length = 15, label=u'Pincode')


    def save(self, *args, **kwargs):
        new_user = super(MyRegistrationForm, self).save(*args, **kwargs)

        #put them on the User model instead of the profile and save the user
        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.save()

        #get the profile fields information
        gender = self.cleaned_data['gender']
        ...
        pincode = self.cleaned_data['pincode']

        #create a new profile for this user with his information
        UserProfile(user = new_user, gender = gender, ..., pincode = pincode).save()

        #return the User model
        return new_user
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!