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?

有帮助吗?

解决方案

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

其他提示

You can get the validated data from the form using cleaned_date:

username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']

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

Now I think your approach has serious problems since you are saving the form again after creating the user object, also the User object expects the password field to be a hash of the password and some meta data, etc. I highly recommend you use django-registration (or at least have a look at it) which handles all this stuff for you in addition to email validation, all you need is to provide the templates(and also you can find some templates for it like this )

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top