DJango background design

Keywords: Django Database

 

I. create administrator

  • Django provides admin background for unified management of users, permissions and permission groups, and super user initialization method.
  • Initialize command line:
python3 manage.py createsuperuser
  • Follow the prompts to set the user name, mailbox, and password:
User name (leave blank to use 'admin'): admin
//Email address: XX xx@xx.com
Password: 
Password (again): 

Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.


II. Modify admin.py
Only need these three lines of code, we can have a strong background!

from django.contrib import admin
from .models import class_name        #Import the classes defined in models.py
 
 
admin.site.register(class_name)        

Visit http://localhost:8000/admin/ Enter the set account number and password to see:

 

Click Articles and add several Articles. You can see:

We will find that all articles are called article objects, which is definitely not good. For example, if we want to modify them, how do we know which one to modify?

Modify models.py in blog
Add a str function to the class class to refresh the background page, and you will see:

Therefore, it is recommended to write a str function when defining a Model.

 

III. display other field related contents in the background list

Backstage has been basically done, but if we need to show some other fields, how to do it?

from django.contrib import admin
from .models import Article                #Import database table class

class Article_Admin(admin.ModelAdmin):    
 
        list_display = ('title','pub_date','update_time',)    #Use list? Dispaly the list of database tables

        admin.site.register(Article,Article_Admin)         #First parameter: database table class; second parameter: list displayed class

List display is to configure the fields to be displayed. Of course, it can also display non field contents or field related contents, such as:

class Person(models.Model):

    first_name = models.CharField(max_length=50)

    last_name = models.CharField(max_length=50)


    def my_property(self):

        return self.first_name + ' ' + self.last_name

        my_property.short_description = "Full name of the person"

    full_name = property(my_property)


In admin.py

from django.contrib import admin

from .models import Article, Person


class ArticleAdmin(admin.ModelAdmin):

    list_display = ('title', 'pub_date', 'update_time',)


class PersonAdmin(admin.ModelAdmin):

    list_display = ('full_name',)


admin.site.register(Article, ArticleAdmin)

admin.site.register(Person, PersonAdmin)

 

Posted by divadiva on Mon, 28 Oct 2019 14:34:07 -0700