pawi552

user_register

Aug 26th, 2014
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. def user_register(request):
  2.     # Like before, get the request's context.
  3.     context = RequestContext(request)
  4.  
  5.     # A boolean value for telling the template whether the registration was successful.
  6.     # Set to False initially. Code changes value to True when registration succeeds.
  7.     registered = False
  8.  
  9.     # If it's a HTTP POST, we're interested in processing form data.
  10.     if request.method == 'POST':
  11.         # Attempt to grab information from the raw form information.
  12.         # Note that we make use of both UserForm and UserProfileForm.
  13.         user_form = UserForm(data=request.POST)
  14.  
  15.         # If the two forms are valid...
  16.         if user_form.is_valid():
  17.             # Save the user's form data to the database.
  18.             user = user_form.save()
  19.  
  20.             # Now we hash the password with the set_password method.
  21.             # Once hashed, we can update the user object.
  22.             user.set_password(user.password)
  23.             user.save()
  24.  
  25.             # Now sort out the UserProfile instance.
  26.             # Since we need to set the user attribute ourselves, we set commit=False.
  27.             # This delays saving the model until we're ready to avoid integrity problems.
  28.  
  29.             # Update our variable to tell the template registration was successful.
  30.             registered = True
  31.             return HttpResponseRedirect('/login')
  32.  
  33.         # Invalid form or forms - mistakes or something else?
  34.         # Print problems to the terminal.
  35.         # They'll also be shown to the user.
  36.         else:
  37.             # jeśli email istnieje (bo mail zapisałem pod postacią username...)
  38.             if "username" in user_form.errors:
  39.                 print("User with that mail is already registered.")
  40.                 return render(request, 'bank/register.html', {
  41.                     'error_message': "User with that mail is already registered.",
  42.                 })
  43.  
  44.     # Not a HTTP POST, so we render our form using two ModelForm instances.
  45.     # These forms will be blank, ready for user input.
  46.     else:
  47.         user_form = UserForm()
  48.  
  49.     # Render the template depending on the context.
  50.     return render_to_response(
  51.         'bank/register.html',
  52.         {'user_form': user_form, 'registered': registered},
  53.         context)
Advertisement
Add Comment
Please, Sign In to add comment