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):
    try:
      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
      pass
    return self.cleaned_data

Template

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

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

View Code

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

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

  try:
    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
      lNewUser.email = lCustomer.contact_email
      lNewUser.set_password(lForm.cleaned_data['password'])
      lNewUser.save()
      return HttpResponseRedirect('/customers/%d/' % lCustomer.oem.id)

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

Tags: django user password