Taking User Input to create Users in Django

First thing you need to do is create a ModelForm:

forms.py

from django.contrib.auth.models import User

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password')

A ModelForm automatically builds your form off a model you provide. It handles the validations based on the fields.

views.py

from forms import UserForm
from django.contrib.auth import login
from django.http import HttpResponseRedirect

def lexusadduser(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            new_user = User.objects.create_user(**form.cleaned_data)
            login(new_user)
            # redirect, or however you want to get to the main view
            return HttpResponseRedirect('main.html')
    else:
        form = UserForm() 

    return render(request, 'adduser.html', {'form': form}) 

If its a POST request, we create a UserForm from the POST values. Then we check if its a valid form. If it is, we create the user, otherwise we return the form with the errors. If its not a POST request, we send a clean form

template

<form method="post" action="">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Create new user account" />
</form>

Tags:

Django