Making it possible for users to sign up is very easy thanks to the built in authentication system in Django. Let's begin with creating a new Django app for users:
$ python manage.py startapp userprofile
And then we need to append it to a list in the "settings.py" file.
INSTALLED_APPS = [
...
'userprofile',
]
Django comes with a built in database model for users, so this app will only be used for views and templates. Open up userprofile/views.py, it should look like this:
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('frontpage')
else:
form = UserCreationForm()
return render(request, 'userprofile/signup.html', {'form': form})
Most of this code should hopefully start looking familiar and make sense now?
We import a method from Django for logging in the user, and a form for creating the user.
If the form is valid, we store the form in a variable called "user", then we log in the user and redirect to the front page.
Next step then is to create the folder for the template (templates/userprofile) and the template inside "signup.html". It should look like this:
{% extends 'task/base.html' %}
{% block content %}
<div class="edit-tasks">
<h1>Sign up</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button>Sign up</button>
</form>
</div>
{% endblock %}
So yet again, a very simple template where we render a form.
The last step then is to create a url file and also appending it in the main urls.py file. Create a file called urls.py in the new userprofile app:
from django.urls import path
from . import views
urlpatterns = [
path('sign-up/', views.signup, name='signup'),
]
And then add it in the main urls.py file:
from django.urls import path, include
urlpatterns = [
path('', include('userprofile.urls')), # New
path('', include('task.urls')),
path('', include('category.urls')),
]
Try to create a user and see what happens. In the next part, we will handle log in and making a few checks if the user is authenticated or not.
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page
- 16. Separate url files and why
- 17. Adding tasks in the front end
- 18. Editing tasks
- 19. Completing and deleting tasks
- 21. Prettying up the design a little bit
- 22. Make it possible to sign up