Search code examples
pythondjangouser-inputdjango-formsdjango-users

Convert Django ModelForm to use User object


I'm creating a registration form for my site.

I'm going with just the standard field entries of username, email, password in my User object.

The database tables are already created.

Models.py

class RegistrationForm(ModelForm):
    class Meta:
        model = User

views.py

def Registration(request):
    RegForm = RegistrationForm(request.POST or None)
    if request.method == 'POST':
        if RegForm.is_valid():
            newUser = User.objects.create_user(username, email, password)

            RegForm.save()
            try:
                return HttpResponseRedirect('/Newuser/?userNm=' + clearUserName)
            except:
                raise ValidationError(('Invalid request'), code='300')    ## [ TODO ]: add a custom error page here.

My question is, how do I represent these fields:

username, email, password

in this line (from the view):

newUser = User.objects.create_user(username, email, password)

that are part of the RegistrationForm() in models.py ?

Additionally: How do I properly represent this default model (User) in the modelform in forms.py?


Solution

  • To answer your second question:

    Use UserCreationForm to represent registration process for User class, it handles validation and saving for you and you can always extend it (i.e. to add email field)

    User class has a lot of related forms, depending of the use case: authentication, registration, password change etc. read the docs on authentication to find more.

    https://docs.djangoproject.com/en/1.5/topics/auth/default/#module-django.contrib.auth.forms