Python Project Practice III (Web application) article fifth

Source: Internet
Author: User
Tags virtual environment

Continue with the previous section, in this section we will establish a user registration and authentication system that allows users to register their accounts and log in and out. We will create a new application that contains all the features related to handling user accounts. We'll also make a slight change to the model topic, so that each topic belongs to a specific user.

Create a user account

1 Applications Users

We first use command Startapp to create an application called Users: (ll_env) learning_log$ python manage.py startapp users

1.1 Add the application users to settings.py

Installed_apps = (--snip--# my application ' learning_logs ', ' users ',)

In this way, Django will include the application users in the project.

1.2 contains the URL of the application users

Next, we need to modify the urls.py in the project root to include the URLs we will define for the application users:

From Django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [url (r ' ^admin/', include ( admin.site.urls), url (r ' ^users/', include (' Users.urls ', namespace= ' users ')), url (r ", include (' Learning_logs.urls ') , namespace= ' learning_logs ')),]

1.3 Login Page

We first implement the login page functionality. To do this, we'll use the default login view provided by Django, so the URL pattern will be slightly different. In directory learning_log/users/, create a new file named urls.py and add the following code to it:

"" Defines the URL pattern "" from Django.conf.urls import urlfrom django.contrib.auth.views import loginfrom for the application users. Import viewsapp_name= ' users ' urlpatterns = [# login page URL (r ' ^login/$ ', login, {' template_name ': ' users/login.html '},name= ') Login '),]

1.4 Template Login.html

Here is the template login.html, which you should store in directory learning_log/users/templates/users/:

{% extends "learning_logs/base.html"%} {% block content%}  {% if form.errors%}  <p>your username and password didn ' t match. Please try again.</p>  {% endif%}    <form method= "POST" action= "{% url ' users:login '%}" >  {% csrf_ Token%}  {{form.as_p}}  <button name= "Submit" >log in</button>   <input type= "hidden" name= " Next "value=" {% url ' learning_logs:index '%} '/>  </form>   {% endblock content%}

1.5 Link to login screen

The following link is added to the login page in base.html, so that all pages contain it. When the user is logged in, we do not want to display this link, so we nest it in a {% if%} tag:

<p>  <a href= "{% url ' learning_logs:index '%}" >learning log</a>-  <a href= "{% url ' learning _logs:topics '%} ' >Topics</a>  {% if user.is_authenticated%}    Hello, {{user.username}}.  {% Else%}    <a href= "{% url ' users:login '%}" >log in</a>  {% endif%}</p>{% block content%}{% endblock content% }

1.6 Using the Login interface
Please visit http://localhost:8000/admin/, if you are still logged on as an administrator, locate the logout link on the header and click it. After logging out, visit http://localhost:8000/users/login/and you will see a login page similar to the one shown in Figure 19-4. Enter the user name and password that you set in front of the page to enter the index. In the header of this page, a personalized greeting is displayed with your user name.

2 Registration and logoff interface

And the above method is probably the same, not repeat, as follows:

Two let the user have their own data

Users should be able to enter their own proprietary data, so we will create a system that determines the users that each data belongs to, and then restricts access to the page so that users can only use their own data. In this section, we will modify the model topic so that each topic belongs to a specific user. This will also affect the entry, because each entry belongs to a specific topic. Let's start by restricting access to some pages.

1 Restricting access using @login_required

Django provides the adorner @login_required, which allows you to easily achieve this goal: for some pages, only logged-in users are allowed access to them. The adorner (decorator) is the instruction placed before the function definition, and Python modifies the behavior of the function code before the function is run.

--snip--from django.core.urlresolvers Import reversefrom django.contrib.auth.decorators import Login_requiredfrom. Models import Topic, entry--snip--@login_requireddef topics (Request): "" "Show All Themes" ""

We first imported the function login_required (). We use login_required () as an adorner for the View function topics ()--precede it with the symbol @ and login_required, and let Python run login_required () code before running the Code for topics (). The code for login_required () checks that the user is logged on, and Django runs the Code for topics () only if the user is logged on. If the user is not logged in, redirect to the login page.

2 Comprehensive restrictions on access to project "Learning notes"

In the project "Learning notes", we will not restrict access to the home page, the registration page, and the logout page, and restrict access to all other pages.
In the following learning_logs/views.py, the adorner @login_required is applied to each view except index ():

@login_requireddef topics (Request):--snip--@login_requireddef topic (Request, TOPIC_ID):--snip--@login_requireddef New_topic (Request):--snip--@login_requireddef new_entry (Request, topic_id):--snip--@login_requireddef edit_entry ( Request, entry_id):--snip--

3 Associating data to users

Now, you need to associate the data to the users who submit them. We simply associate the highest level of data with the user, so that the lower data is automatically linked to the user. For example, in the project learning notes, the highest level of data for an application is a theme, and all entries are associated with a specific topic. As long as each topic belongs to a specific user, we can determine the owner of each entry in the database.

The following modifies the model topic, where it adds a foreign key associated to the user. After doing this, we must migrate the database. Finally, we have to modify some views to show only the data associated with the currently logged-on user.

4 Determine which users are currently

When we migrated the database, Django would modify the database so that it could store the association between the subject and the user, and look at the IDs of all the users that were created. To do this, start a Django shell session and execute the following command:

3 Migrating databases

Once you know the user ID, you can migrate the database.

You can now perform the migration. To do this, execute the following command in the active virtual environment:

Verify that the migration is successful

Next, protect the user's theme, protect the page, link the new theme to the current user, and so on, no longer detailed! Learn this first!

Python Project Practice III (Web application) article fifth

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.