Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking User Input to create Users in Django

Tags:

django

I would like to create/add new users to my app in Django using the user input. I am using the default login provided by django. I am trying to add users to the default login. The example in https://docs.djangoproject.com/en/dev/topics/auth/:

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', '[email protected]', 'john password')

passes the username and password. But i would like this to happen with user input. How do i do this?

Need some guidance...

I tried this but it doesn't seem to work:

def lexusadduser(request):
    """
    add user
    """
    if request.method == "POST":
        user.save()

        auth_user = authenticate(username=user.username,password=user.password)

        if auth_user is not None:
            lexusmain(request)
        else:
            return render('adduser.html') 
like image 425
lakshmen Avatar asked Jul 02 '12 03:07

lakshmen


1 Answers

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>
like image 168
jdi Avatar answered Oct 18 '22 04:10

jdi