Creating Users in Django

January 14, 2011

I wanted to give my users the ability to create a Django user at a particular point in the web site flow. This must be done without going into the Django admin, but can only be done by users who have admin access - this change simplifies their workflow.

Here's the code I came up with.

Form Code

The form needs to ask for a username, password (twice) and then validate that the passwords match.

class CustomerCreateNewLoginForm(forms.Form):
  Form for creating new login
  username = forms.CharField()
  password = forms.CharField(widget=forms.PasswordInput)
  check_password = forms.CharField(widget=forms.PasswordInput)

  def clean(self):
      if self.cleaned_data['password'] != self.cleaned_data['check_password']:
        raise forms.ValidationError("Passwords entered do not match")
    except KeyError:
      # didn't find what we expected in data - fields are blank on front end.  Fields
      # are required by default so we don't need to worry about validation
    return self.cleaned_data


Here's the part of the template that presents the form.

<form method="post" action=".">
  <tr><td>&nbsp;</td><td><input type="submit" value="Create User" /></td></tr>

View Code

Finally, here's the view that both shows the original form and accepts the form submission.

def create_login(request, pCustomerSerial):
  Create a login for a new customer.  
  if request.user.is_staff == False:
    raise Http404

    lCustomer = Customer.objects.filter(id=pCustomerSerial)[0]
  except IndexError:
    raise Http404

  lForm = CustomerCreateNewLoginForm()

  if request.POST:
    lForm = CustomerCreateNewLoginForm(request.POST)
    if lForm.is_valid():
      lNewUser = User()
      lNewUser.username = lForm.cleaned_data['username']
      lNewUser.first_name = lCustomer.contact_person = lCustomer.contact_email
      return HttpResponseRedirect('/customers/%d/' %

  return render_auth(request, 'create_customer_login.html', {'Customer' : lCustomer,
                                                             'form' : lForm})

Tags: django user password