Django static files, middleware, admin background management

Static File

Use of static files

The css files, js files and pictures used in web pages are called static files.
1) Create a new static folder under the project.

2) The physical directory where the configuration static file is located.Settings.py

  • STATIC_URL sets the url corresponding to accessing a static file.
  • STATICFILES_DIRS sets the physical directory in which the static file resides.

Path to dynamically generate static files

That is, no matter how your STATIC_URL changes, it also has no effect on static file url fetching on the page

settings.py

# Set access to static files url address
# http://127.0.0.1:8000/static/images/mm.jpg, which gives you direct access to pictures
STATIC_URL = '/static/'
# STATIC_URL = '/abc/'

# Set the physical directory where static files are stored
# Django Order of Finding Static Files: Configured first STATICFILES_DIRS Go down and apply if you can't find it static Look below
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

static_test.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Static File Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<img src="/static/images/mm.jpg" alt="mm">
<img src="/abc/images/mm.jpg" alt="mm">

//Get the STATIC_URL dynamically and stitch the static file path:<br>
<img src="{% static 'images/mm.jpg' %}" alt="mm">

</body>
</html>

Matching function

def static_test(request):
    """Static File"""
    return render(request, 'booktest/static_test.html')

 

middleware

Middleware functions are function interfaces reserved for us by the django framework, allowing us to intervene in the process of requests and responses.

Using Middleware

1) Create a new middleware.py file in the application.

2) Define the middleware class.

Define the middleware reservation function in the class.

  • _u init_u: Called when the server responds to the first request.
  • process_request: Called before a request object is generated for url matching.
  • process_view: After the url matches, before the view function is called.
  • process_response: After the view function is called, the content is returned before the browser.
  • process_exception: The view function is called when an exception occurs.

If the process_exception function is included in more than one registered middleware class, the order of invocation is the opposite of the order of registration.
3) Register the middleware class.

 

Use middleware for login judgment cases

Get the browser-side ip address, using the META property of the request object:

request.META['REMOTE_ADDR']

 

demand

When we need to disable access to some malicious ips, we need to get the user's ip and then build a list of prohibited IPS to determine if the ip is in the prohibited list or if it is malicious, it is prohibited.
Otherwise, to return to the page of the response, it is true that we can define a decorator to judge each function, but this is not the best option, we can use middleware.

Single function judgment

def index(request):
    """home page"""
    user_ip = request.META['REMOTE_ADDR']
    print(user_ip)
    if user_ip in EXCLUDE_IPS:
        return HttpResponse("<h2>Forbidden</h2>")
    return render(request, 'booktest/index.html')

 

Decorator Judgment

def ban_ip(view_func):
    """Used to prohibit malicious acts ip Decorators for"""
    def wrapper(request, *args, **kwargs):
        user_ip = request.META['REMOTE_ADDR']
        print(user_ip)
        if user_ip in EXCLUDE_IPS:
            return HttpResponse("<h2>Forbidden</h2>")
        else:
            return view_func(request, *args, **kwargs)
    return wrapper

@ban_ip
def index(request):
    """home page"""
    return render(request, 'booktest/index.html')

 

Middleware steps

  • 1. Create a new middleware.py file with a random name under the app, but generally use this one.
  • 2. Write middleware code;
  • 3. Register the middleware in settings;

Middleware Judgment

from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse

class BanIpMiddleware(MiddlewareMixin):
    """Middleware Class"""
    EXCLUDE_IPS = ['127.0.0.1']

    @staticmethod
    def process_view(request, view_func, *args, **kwargs):
        """View functions are called before they are called"""
        user_ip = request.META['REMOTE_ADDR']
        if user_ip in BanIpMiddleware.EXCLUDE_IPS:
            return HttpResponse("<h2>Forbidden</h2>")

Register Middleware

MIDDLEWARE = [
    'booktest.middleware.BanIpMiddleware',
]

 

Middleware Execution Order

The execution order of the middleware is generally based on the registration order in the settings file, especially if the process_exception function is included in more than one of the registered middleware classes, the invocation order is the opposite of the registration order.

_u init_u is called only after the server restarts, on the first request, and no later requests will be called.

Middleware Execution Order Sample Code

class TestMiddleware(MiddlewareMixin):
    """Middleware Class"""
    def __init__(self, get_response=None):
        """Called when the first request is received after the server restarts"""
        # get_response The parameter is required and refers to the next middleware or view function(If it is the last Middleware). 
        super().__init__()
        self.get_response = get_response
        print("-----init-----")

    @staticmethod
    def process_request(request):
        """produce request After the object, url Called before matching"""
        print("-----process_request-----")

    @staticmethod
    def process_view(request, view_func, *args, **kwargs):
        """url After matching, call before view function call"""
        print("-----process_view-----")

    @staticmethod
    def process_response(request, response):
        """After view function, answer before returning to browser"""
        print("-----process_response-----")
        return response
        
# Execution results:
# -----init-----
# -----process_request-----
# -----process_view-----
# -----process_response-----


class ExceptionTest1Middleware(MiddlewareMixin):
    @staticmethod
    def process_exception(request, exception):
        """Called when an exception occurs to a view function"""
        print("-----process_exception1-----")
        print(exception)


class ExceptionTest2Middleware(MiddlewareMixin):
    @staticmethod
    def process_exception(request, exception):
        """Called when an exception occurs to a view function"""
        print("-----process_exception2-----")

 

admin background management

Use of admin

  • 1) Localization.Language and time zone localization.
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
  • 2) Create a super administrator.
python mange.py createsuperuser
  • 3) Register model classes.
  • 4)
  • 4.1. Customize the administration page.
  • 4.2. Customize model management classes.
  • 4.3. Add the second parameter to the register function when registering the model class, which is the name of the custom model management class.

List Page Options

List Page Options Sample Code

models.py

class AreaInfo(models.Model):
    """Regional Model Class"""
    # Area Name
    atitle = models.CharField(verbose_name="Area Name", max_length=20)
    # Self-Associated Attributes
    aParent = models.ForeignKey('self', null=True, blank=True)

    # stay admin Show area names after entering the table
    def __str__(self):
        return self.atitle

    # Definition title Column, providing display atitle
    def title(self):
        return self.atitle
    title.admin_order_field = 'id'  # Definition title Sort Columns
    title.short_description = 'Area Name'  # Definition title Column name displayed by column

    def parent(self):
        if self.aParent is None:
            return ''
        return self.aParent.atitle
    parent.short_description = 'Parent Area Name'

 

admin.py

class AreaInfoAdmin(admin.ModelAdmin):
    """Regional Model Management Class"""
    list_per_page = 10  # Specify that 10 pieces of data are displayed per page
    list_display = ['id', 'atitle', 'title', 'parent']  # Specify what is displayed on the page
    actions_on_bottom = True  # Open below action frame
    actions_on_top = False  # Close Built On action frame
    list_filter = ['atitle']  # Filter orchid on right side of page table
    search_fields = ['atitle']  # Search box above list page


admin.site.register(models.AreaInfo, AreaInfoAdmin)

Note: list_display can not only write properties of model classes, but also methods.

Display effect

 

Edit Page Options

Initial Effect Chart

fields control display field order

class AreaInfoAdmin(admin.ModelAdmin):
    fields = ['aParent', 'atitle']  # Control the order in which fields are displayed on the edit page

After changing the order

Grouped display

class AreaInfoAdmin(admin.ModelAdmin):
    """Regional Model Management Class"""
    fieldsets = (
        ('basic', {'fields': ['atitle']}),
        ('senior', {'fields': ['aParent']})
    )

Group Display Effect Graph

It should be noted that fields and fieldsets cannot be used simultaneously.

 

Associated Objects/Controls show sub-regions below this region

Block Embedding

# Block Embedding
class AreaStackedInline(admin.StackedInline):
    # Write names of multiple classes
    model = models.AreaInfo  # Associate child objects
    extra = 2  # Control redundant rows/Edit 2 extra child objects

class AreaInfoAdmin(admin.ModelAdmin):
    """Regional Model Management Class"""
    inlines = [AreaStackedInline]

Table Embedding

class AreaTabularInline(admin.TabularInline):
    model = models.AreaInfo  # Associate child objects
    extra = 2  # Control redundant rows/Edit 2 extra child objects

class AreaInfoAdmin(admin.ModelAdmin):
    """Regional Model Management Class"""
    inlines = [AreaStackedInline]

Table Embedding Effect Graph

Block embedding and table embedding actually display the same content, but knowledge display styles are different.

Keywords: Python Django

Added by aman_batra on Thu, 29 Aug 2019 19:52:10 +0300