django 2 by example --- Creating a social website project
Django 2 by example
-- Creating a social website project
We will create a social application that will allow users to share images they find on the internet.
We will need to build the following elements for this project:
- An authentication system for users to register, log in, edit their profile, and change or reset their password.
- A followers' system to allow users to follow each other
- A functionality to display shared images and implement a bookmarklet【小书签】 for users to share images from any website
- An activity stream for each user that allows users to see the content uploaded by the people they follow
This chapter addresses the first point mentioned in the preceding【上述的,前面的】 list.
Starting your social website project
Open the terminal, and use the following commands to create a virtual environment for your project and activate it:
mkdir env
virtualenv env/bookmarks
source env/bookmarks/bin/activate
The shell prompt will display your active virtual environment, as follows:
(bookmarks)laptop: ~ zenx$
Install Django in your virtual environment with the following command:
pip install Django==2.0.5
Run the following commands to create a new project:
django-admin startproject bookmarks
After creating the initial project structure, use the following commands to get into your project directory and create a new application named account:
cd bookmarks/
django-admin startapp account
Remember that you should activate the new application in your project by adding it to the INSTALLED_APPS setting in the settings.py file. Place it in the INSTALLED_APPS list before any of the other installed apps:
INSTALLED_APPS = [
'account.apps.AccountConfig',
# ...
]
We will define Django authentication templates later on【随后, 稍后】.By placing our app first in the INSTALLED_APPS setting, we ensure that our authentication templates will be used by default instead of any other authentication templates contained in other apps. Django looks for templates by order of app appearance in the INSTALLED_APPS setting.
Run the next command to sync the database with the models of the default applicaitons included in the INSTALLED_APPS setting:
python manage.py migrate
You will see that all initial Django database migrations get applied. We will build an authentication system into our project using the Django authentication framework.
Using the Django authentication framework
Django comes with a built-in authentication framework that can handle user authentication, sessions, permissions, and user groups. The authenticaiton system includes views for common user actions such as login, logout, password change, and password reset.
The authentication framework is located at django.contrib.auth and is used by other Django contrib packages. Remember that you have already used the authentication framework in chapter 1, Building a Blog Application, to create a superuser for your blog applicaiton to access the administration site.
When you create a new Django project using the startproject command, the authentication framework is included in the default settings of your project. It consists of the django.contrib.auth applicaiton and the following two middleware classes found in the MIDDLEWARE setting of your project:
- AuthenticationMiddleware: Associates users with requests using sessions
- SessionMiddleware: Handles the current session across requests
A middleware is a class with methods that are globally executed during the request or response phase. You will use middleware classes on several occasions【时机,场合】 throughout【贯穿整个时期】 this book, and you will learn to create custom middleware in Chapter 13, Going Live.
The authentication framework also includes the following models:
- User: A user model with basic fields; the main fields of this model are username, password, email, first_name, last_name, and is_active
- Group: A group model to categorize【将...分类, 把...加以归类】 users
- Permission: Flags for users or groups to perfrom certain actions
The framework also includes default authentication views and forms that we will use later.
Creating a lgoin view
We will start this section by using the Django authentication framework to allow users to log in to our website. Our view should perform the following actions to log in a user:
1. Get the username and password by posting a form
2. Authenticate the user against the data stored in the database
3. Check whether the user is active
4. Log the user into the website and start an authenticated session
First, we will create a login form. Create a new forms.py file in your account application directory and add the following lines to it:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
This form will be used to authenticate users against the database.
Note that we use the PasswordInput widget to render its HTML input element, including a type="password" attribute,so that the browser treats it as a password input. Edit the views.py file of your account application and add the following code to it:
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user=authenticate(request,username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request,user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
This is what our basic login view does: when the user_login view is called with a GET request, we instantiate a new login form with form=LoginForm() to display it in the template. When the user submits the form via POST, we perform the following actions:
1. Instantiate the form with the submitted data with form = LoginForm(request.POST)
2. Check whether the form is valid with form.is_valid(). If it is not valid, we display the form errors in our template(for example, if the user didn't fill in one of the fields)
3. If the submitted data is valid, we authenticate the user against the database using the authenticate() method. This method takes the request object, the username, and the password parameters and returns the user object if the user has been successfully authenticated, or None otherwise. If the user has not been authenticated, we return a raw HttpResponse, displaying the Invalid login message.
4. If the user was successfully authenticated, we check whether the user is active, accessing its is_active attribute. This is an attribute of Django's user model. If the user is not active, we return an HttpResponse that displays the Disabled account message.
5. If the user is active, we log the user into the website. We set the user in the session by calling the login() method and return the Authenticated successfully message.
Note the difference between authenticate and login: authenticate() checks user credentials and returns a user object if they are right; login() sets the user in the current session.
Now, you will need to create a URL pattern for this view. Create a new urls.py file in your account application directory and add the following code to it:
from django.urls import path
from . import views
urlpatterns = [
# post views
path('login/', views.user_login, name='login'),
]
Edit the main urls.py file located in your bookmarks project directory, import include, and add the URL patterns of the account application, as follows:
from django.conf.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls')),
]
The login view can now be accessed by a URL. It is time to create a template for this view. Since you don't have any templates for this project, you can start by creating a base template that can be extended by the login template. Create the following files and directories inside the account application directory:
templates/
account/
login.html
base.html
Edit the base.html file and add the following code to it:
{% load staticfiles %}
<! DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
This will be the base template for the website. As we did in our previous project, we include the CSS styles in the main template. You can find these static files in the code that comes along with【随同】 this chapter. Copy the static/ directory of the account application from the chapter's source code to the same location in your project so that you can use the static files.
The base template defines a title block and a content block that can be filled with content by the templates that extend from it.
Let's fill in the template for our login form. Open the account/login.html template and add the following code to it:
{% extends "base.html" %}
{% block title %}Log-in{% endblock %}
{% block content %}
<h1>Log-in</h1>
<p>Please, use the following form to log-in:</p>
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Log in"></p>
</form>
{% endblock %}
This template includes the form that is instantiated in the view. Since our form will be submitted via POST, we will include the {% csrf_token %} template tag for CSRF protection. You learned about CSRF protection in chapter 2, Enhancing Your Blog with Advanced Features.
There are no users in your database, yet. You will need to create a superuser first in order to be able to access the administration site to manage other users. Open the command line and execute python manage.py createsuperuser. Fill in the desired【期望的】 username, email, and password. Then, run the development server using the python manage.py runserver command and open http://127.0.0.1:8000/admin/ in your browser. Access the administration site using the credentials of the user you just created. You will see the Django administration site, including the User and Group models of the Django authentication framework.
It will look as follows:
Create a new user using the administration site and open http://127.0.0.1:8000/account/login/ in your browser. You should see the rendered template, including the login form: