Guest User

Untitled

a guest
Aug 7th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. from django.shortcuts import render, redirect
  2. from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
  3. from django.contrib.auth import login, authenticate, logout
  4.  
  5.  
  6. # Create your views here.
  7. def signup_user(request):
  8. if request.method == 'POST':
  9. form = UserCreationForm(request.POST)
  10. if form.is_valid(): # first see whether all is good
  11. form.save() # at this point the new user is created
  12. # now we want to log them in right away, for UX reasons
  13. # therefore we'll fetch username and pwd from the form
  14. username = form.cleaned_data.get('username')
  15. # ATTENTION: it's important to fetch 'password1' (which is
  16. # the original password) instead of just 'password', which
  17. # does not exist! However, .get() will not fail with an
  18. # exception if it doesn't find the key in the dictionary!
  19. password = form.cleaned_data.get('password1')
  20. user = authenticate(username=username, password=password)
  21. login(request, user)
  22. return redirect('/home')
  23. else:
  24. # if the user is not submitting, create an empty form
  25. # this runs the first time the user accesses the site
  26. form = UserCreationForm()
  27. return render(request, 'signup.html', {'form': form})
  28.  
  29. def login_user(request):
  30. if request.method == 'POST':
  31. # It's really important to remember to put `data=request.POST`
  32. # The AuthenticationForm works a little different than the other
  33. # forms, so the request is not its default first input...
  34. # messy - but that's how it is!
  35. form = AuthenticationForm(data=request.POST)
  36. if form.is_valid():
  37. username = form.cleaned_data.get('username')
  38. password = form.cleaned_data.get('password')
  39. user = authenticate(username=username, password=password)
  40. login(request, user)
  41. return redirect('/home')
  42. else:
  43. form = AuthenticationForm()
  44. return render(request, 'login.html', {'form': form})
  45.  
  46. def logout_user(request):
  47. logout(request)
  48. return redirect('/login')
  49.  
  50. def home(request):
  51. return render(request, 'home.html', {})
Add Comment
Please, Sign In to add comment