We now have a blogging system that allows users to log in locally. If someone likes your post, they might sign up as a local user and start chatting with you.

But the headache is that users may be reading a lot of great blogs on the Internet every day, and if every blog has to sign up to comment, it is not a small burden for users. For grassroots sites such as personal blogs, users may not bother to sign up, and you lose a potential “fan”.

A popular solution is to allow users to log in through a third party, that is, through GitHub, Weibo and other well-known community authorization, so as to log in to your site, without the trouble of registration.

Django-allauth is a powerful library that not only provides a complete solution for local registration, login, and management, but also supports dozens of third-party login methods such as GitHub, Twitter, Weibo, wechat, and Even Baidu.

The local login

Take a look at how django-Allauth’s local login is configured.

Install django – allauth:

(env) > pip install django-allauth
Copy the code

Modifying a configuration file:

my_blog/settings.py

...


TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                # allauth startup required
                'django.template.context_processors.request',
            ],
        },
    },
]


AUTHENTICATION_BACKENDS = (
    # Djangos can be logged in independently of Allauth
    'django.contrib.auth.backends.ModelBackend'.Configure allauth unique authentication method, such as email login
    'allauth.account.auth_backends.AuthenticationBackend',
)


INSTALLED_APPS = [
    ...
    # allauth startup required
    'django.contrib.auth'.'django.contrib.messages'.'django.contrib.sites'.'allauth'.'allauth.account'.'allauth.socialaccount'.You can add the required third party login
    'allauth.socialaccount.providers.github'.'allauth.socialaccount.providers.weibo'. ]# set up a site
SITE_ID = 1

Redirect address after successful login
LOGIN_REDIRECT_URL = '/article/article-list'.Copy the code

Note that some of the content in the above configuration is already present when the project is created. Check to see if it is included in your project. Some of the content is completely new, so don’t leave it out.

Django-allauth is also an app, so you need to assign it a URL:

my_blog/urls.py

...

urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),... ]Copy the code

The final step is to migrate the data:

(env) > python manage.py migrate
Copy the code

And that’s it!

Enter the default login page address for Django-allauth:

http://127.0.0.1:8000/accounts/login/
Copy the code

The following page is displayed:

Setting up the homepage

As of now, our blog has not been assigned a home page address.

The front page of a blog site is usually the list of articles itself, so add this route to my_blog/urls.py:

my_blog/urls.py

...
from article.views import article_list

urlpatterns = [
    # home
    path(' ', article_list, name='home'),... ] .Copy the code

Change the redirection address after login successfully:

my_blog/settings.py

...
# redirect the URL
#LOGIN_REDIRECT_URL = '/article/article-list'
LOGIN_REDIRECT_URL = '/'

Copy the code

This will have the address http://127.0.0.1:8000 home page.

Beautify the template

The template that comes with Django-Allauth is rudimentary and needs to be overridden for your site to use.

Remember that virtual environment we’ve been using? Yes, all third-party libraries needed to run a project are stored in a folder in the virtual environment, which in this tutorial is the ENV folder. Find the following path:

env\Lib\site-packages\allauth\templates\account\login.html
Copy the code

This login. HTML is the original login template file. It’s possible to modify this file directly to optimize the page, but doing so would be silly, because every time you upgrade your library, or switch computers for deployment, the template goes back up again.

The correct approach is to copy the login. HTML file into the templates folder of your own project. That is, you need to create exactly the same path in your project:

templates\account\login.html
Copy the code

Django prioritizes looking for template files in your project, so you can override them as long as the relative paths are the same.

Then you can have fun with your custom style.

The reference code is as follows:

templates\account\login.html {% extends "base.html" %} {% load i18n %} {% load account socialaccount %} {% block title {% endblock %} {% block content %}<div class="container">
    <div class="row">
        <div class="col-12">
            <br>
            {% get_providers as socialaccount_providers %}
            {% if socialaccount_providers %}
            <p>{% blocktrans with site.name as site_name %} Log in to an existing local account or<a href="{{ signup_url }}">registered</a>The new account. You can also log in through a third party :{% endBlocktrans %}</p>

            <div class="socialaccount_ballot">
                <h5 class="mb-2 mt-4">Third party Login:</h5>
                <ul class="socialaccount_providers">
                  {% include "socialaccount/snippets/provider_list.html" with process="login" %}
                </ul>
                <h5 class="mb-2 mt-4">Local Login:</h5>
            </div>

            {% include "socialaccount/snippets/login_extra.html" %}

            {% else %}
            <p>{% blocktrans %}If you have not created an account yet, then please
            <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p>
            {% endif %}
            <div class="col-6">
                <form class="login" id="login_form" method="POST" action="{% url 'account_login' %}">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="id_login">Account:</label>
                        <input type="text" name="login" placeholder="Please enter user name or Email" autofocus="autofocus" required
                            id="id_login" class="form-control" />
                        <small class="form-text text-muted ml-1">Don't have an account yet?<a href="{% url 'account_signup' %}" style="color: cornflowerblue; ">Register a new account</a>
                        </small>
                    </div>
                    <div class="form-group mb-1">
                        <label for="id_password">Password:</label>
                        <input type="password" name="password" placeholder="Please enter your password" required id="id_password"
                            class="form-control" />
                        <small class="form-text text-muted ml-1">
                            <a class="secondaryAction layui-text" href="{% url 'account_reset_password' %}">Forget your password?</a>
                        </small>
                    </div>
                    <div class="custom-control custom-checkbox mb-2">
                        <input type="checkbox" name="remember" id="id_remember" checked class="custom-control-input" />
                        <label for="id_remember" class="custom-control-label">Keep the login</label>
                    </div>
                    <button class="primaryAction btn btn-primary" type="submit" hidden id="submit_login">confirm</button>
                    <button class="primaryAction btn btn-primary" type="button" id="on_submit_login">confirm</button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}
Copy the code

The actual effect is as follows:

In addition to the login page, all other pages such as registration, email authentication page and mail, third party login page can be overwritten in this way. Tutorial will not repeat, readers please try their own.

registered

Next look at the registration page.

Click the register button and you will see the following page:

Note that if you fill in your email address, the site will automatically send you a certified email address. Therefore, the mailbox configuration described in the previous section must be correct, otherwise you will get a ConnectionRefusedError error. The configuration items are as follows:

my_blog/settings.py

# SMTP server
EMAIL_HOST = 'your smtp'
# mailbox name
EMAIL_HOST_USER = 'your email'
# Email password
EMAIL_HOST_PASSWORD = 'your password'
# Port to send mail
EMAIL_PORT = 25
Whether to use TLS
EMAIL_USE_TLS = True
The default sender
DEFAULT_FROM_EMAIL = 'your email'
Copy the code

Remember to modify your own email configuration.

Note also that the account registered with Django-allauth is generic to django’s built-in local account. That is, an account created using the built-in User can be logged in to through Django-allauth.

With Django-Allauth, all the user login, registration, and password reset modules written in the previous tutorial are eliminated. Well, in that case, isn’t the blogger ripping people off by taking such a detour? Well, learning is about doing things in different ways…

Making the login

The local login is done, but the third party login is the focus.

Since GitHub is the easiest third-party login, I’ll use this as an example.

As a qualified programmer, how can you not have a GitHub account!

Making registration request

The first step to creating third-party logins is to create the OAuth application on GitHub. Log in to GitHub and go to the address:

https://github.com/settings/applications/new
Copy the code

If not, please check OAuth’s Settings in your home page.

After entering the page, fill in the following contents:

Enter the local IP address, which can be changed to the actual domain name after online deployment.

Note the contents of the callback URL. Click OK to get the information for the application:

The Client ID and Client Secret are the credentials to be used.

Django Backend Configuration

Then set up the Django background.

Enter the background, you will find several more columns:

Open Sites and change example.com to the blog domain name. Change it to the local IP address during development:

Then go to Social Applications and add an application like this:

Note that in the Sites bar at the bottom, be sure to select the site you just added to the right.

Go back to the django-Allauth login page and click on Github to log in:

GitHub login is implemented.

Allauth configuration items

Pick out some of the more important ones.

ACCOUNT_EMAIL_VERIFICATION = ‘optional’/’ Mandatory ‘/’ None ‘: When it is MANDATORY, locally registered users must verify the mailbox before logging in. Neither optional nor None requires an authentication email address. The difference is that optional still sends an authentication email, while None does not send an authentication email.

SOCIALACCOUNT_EMAIL_VERIFICATION = ‘optional’/’ Mandatory ‘/’ None ‘: This applies to registration of third-party accounts.

ACCOUNT_AUTHENTICATION_METHOD = ‘username_email’/’user’/’email’ : Specifies the login method, that is, the username, email address, or both.

ACCOUNT_EMAIL_REQUIRED = True/False: Specifies whether the email address must be filled in when a local user is registered.

In addition, there are many configuration items, please refer to the official documentation for details.

conclusion

Learn how to use Django-Allauth to log in locally and on GitHub. The login methods of Microblog and wechat generally follow this process; Although the interface of weibo is loaded in this chapter, it is not configured due to the limited space. Please refer to the official documents to implement it. It should be noted that the third party login in China probably takes one or two days to apply for and review, which is more troublesome.

In addition, the finishing work of writing entry and deleting old features is left to the readers themselves.

As a reminder, the reverse resolution address for login is {% URL ‘account_login’ %}, registered as {% URL ‘account_signup’ %}. These can be found in the original template file or on the official website.


  • If you have any questions please leave a message on Doucet’s personal website and I will reply as soon as possible.
  • Or Email me a private message: [email protected]
  • Project code: Django_blog_tutorial