Hello, everyone. This is the latest edition of Learning Python. What can YOU do? Django tutorials from scratch to finally successfully deploy live projects. In this section, we’re going to write a 404 page.

Peekpa.com official address: Peekpa.com

PI ye each article, are configured with the corresponding code. The code Tag for this article is Post_023

In the first few sections, we are aiming at the functions of the website, for the development, in fact, the basic functions have been almost completed, this section, we are going to manage the permissions of the website.

Rights Management Analysis

Why do YOU need permission management?

And the reason for that is that we developed Login in lecture 11, when we created administrator accounts, and then later in lecture 11, we developed the backend management system.

Although we have administrator account and login function, careful students will find that the CMS system we developed before can be used without login.

This is a Bug ah, this is the problem ah, if the launch of the formal environment, your system is not just casually let others log in the background, but also manage your articles?

So today, we are going to add permissions to the CMS system, so that users have to log in to use the CMS system, if not logged in, they can’t use the CMS system.

The principle,

If a page is not logged in, it cannot be accessed. The only thing that can do that is request.

Notice, every time we’re writing a view function, whether it’s a POST method or a GET method or whatever, we’re passing a request parameter, and it’s mandatory. WSGIRequest: WSGIRequest:

It is derived from the Django.http.HttpRequest class.

Docs.djangoproject.com/en/3.0/ref/…

For us, if we want to implement login access, we can see that HttpRequest has a variable called user. We can use this variable to make a judgment.

The core code is actually the following:

if request.user.is_authenticated:
    ... # Do something for logged-in users.
else:...# Do something for anonymous users.
Copy the code

We will implement permission management by means of modifiers. What is a decorator? It’s a modifier written at @xxx in front of a method. Used to decorate the entire method.

Appropriate method

Our previous Login page had a Login method, and we need to write a logout method and put it in the Navbar at the top of the CMS.

def logout_view(request):
    logout(request)
    return redirect(reverse('cms:login'))
Copy the code

Permissions of actual combat

Since we want permission management, we should create a decorators.py file under the PeekpaUser application and write decorators inside it.

def peekpa_login_required(func):
    def wrapper(request, *args, **kwargs):
        if request.user.is_authenticated:
            return func(request, *args, **kwargs)
        else:
            if request.is_ajax():
                return restful.unauth(message='Please login first! ')
            else:
                return redirect(reverse('cms:login'))
    return wrapper
Copy the code

So let’s import this decorator into the CMS, add it to the CMs_dashboard and category_manage_view and try it:

@peekpa_login_required
def cms_dashboard(request):
    
@peekpa_login_required
def category_manage_view(request):
Copy the code

This time, we in the browser enter the http://localhost:8000/cms/dashboard/ Dashboard, see page jump to the login page directly:

We can see that the bottom right hand corner of the network, and our http://localhost:8000/cms/dashboard/ is 302, so the page will redirect to the login page.

Also, let’s take a look at the category of the manage page, the address is http://localhost:8000/cms/dashboard/category/manage:

The bottom right shows the same thing. 302 The login page is displayed.

But this time, we go to have a look at the category the publish pages, because we didn’t add this page decorator, the address is http://localhost:8000/cms/dashboard/category/publish:

As you can see, it’s coming straight in, and it’s doing exactly what it did when it was developed. It shows that the modifier still works.

Next, let’s go back to the Category Manage page, log in, and see if we can still access the page:

Once you log in, there is no problem at all. So if we want to add permission validation to the CMS, all we need to do is add the @peekpa_login_required decorator before the view function.

Now, if you’re careful, you might notice that all of our modifiers here are actually methods. Actually in our system, and some view function mapping is actually the view class, such as: http://localhost:8000/cms/dashboard/exchangelink/edit? Exchangelink_id =1, which maps back to ExchangeLinkEditView.

When we open this address without making any changes, we can successfully jump to ExchangeLink’s change page:

So, we haven’t done anything to protect the view class. So, we have to use the @method_decorator decorator here, as follows:

@method_decorator(peekpa_login_required, name='get')
class ExchangeLinkEditView(View):
    def get(self, request):
        exchangelink_id = request.GET.get('exchangelink_id')
        exchangeLink = ExchangeLink.objects.get(pk=exchangelink_id)
        context = {
            'item_data': exchangeLink,
            'list_data_status': ExchangeLink.STATUS_ITEMS,
        }
        return render(request, 'cms/exchangelink/publish.html', context=context)
Copy the code

The first variable is the method decorator, and the second name is the method that needs to be decorated. We’ll just apply the GET method here. If YOU want to modify post, name=post; If you want to modify the GET and POST methods, just say name=dispatch.

This time, we go to visit the http://localhost:8000/cms/dashboard/exchangelink/edit? Exchangelink_id = 1:

You’ll notice that the page is automatically redirected to the login page. You also see request 302 in the lower right corner.

404 pages

A 404 page, which I’m sure you’re all familiar with, will look something like this when we start the service and open another page that we haven’t seen before, such as http://127.0.0.1:8000/mm:

When you see this page, here are a few points:

  1. The DEBUG variable in your settings.py file has a value of True
  2. You did not write a 404 page, so you see the system debug error page.

If we want to see the actual 404 page, we need to change DEBUG and ALLOWED_HOSTS to the following values in settings.py:

DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1']
Copy the code

They indicate that the current site is not in debug mode, allowing access to the host address 127.0.0.1

So at this point, we go to http://127.0.0.1:8000/mm again and see something like this:

This white page, in fact, is the system’s own 404 page.

All we need to do is customize our own page by creating a page called 404.html in the template directory:

At this point, we need to restart the server and visit the non-existent page again to see:

How’s that? Is our page customized? Django isn’t powerful enough to customize error handling pages in an easy way.

Technical summary

So just to conclude,

Access permissions and 404:

  1. If you want to restrict user access, use Httprequest.user.
  2. In general, this is done in the form of modifiers;
  3. Method modifier, added directly@xxxBefore a method, class decorator, is used@method_decorator(peekpa_login_required, name='get');
  4. A 404 page is created directly under the template template called404.html“Files will do;
  5. If you want to see what a real 404 page looks like, you have to put the SettingsDEBUG=True, and also setALLOWED_HOSTSThe value of the;
  6. To complete.

The only way to get the code: follow “PI Ye Lu code” and reply “code” to get it.

Long press the two-dimensional code below to pay attention to, if the article is inspiring to you, welcome to look at and forward.