Django-Admin management tool

Source: Internet
Author: User

For a certain type of website, the management interface is very important. He can add, edit, delete site content, but the creation of a management interface cumbersome and repetitive, and the interface is stereotyped; Django can do this tedious work with no less code: it reads the metadata in your schema, and then provides you with a powerful and immediate interface to work with.

Django.contrib is a large set of feature sets, part of the Django CodeBase, which contains:

User Identification System (DJANGO.CONTRIB.AUTH)

Support for anonymous sessions (Django.contrib.sessioins)

User commentary System (django.contrib.comments) and so on;

The Django Automatic management tool is part of the Django.contrib (that is, django.contrib.admin). You can see it in the settings.py of the project Installed_apps:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/8C/04/wKioL1hfarOR84CsAAAUaeQkv3g956.png "title=" 1.png " alt= "Wkiol1hfaror84csaaauaeqkv3g956.png"/>

"Configure Admin Interface"

Activating the Management interface

The Django Admin site is optional, so we can choose to turn it on or off, 1.10.0 is on by default, and the activation steps are as follows:

1, confirm the configuration file within the Installed_apps ' auth ', ' contenttypes ', ' sessions ' is open, Django Configuration management tools need these 3 packages;

2, confirm the configuration file in middleware ' django.middleware.common.CommonMiddleware ', ' Django.contrib.sessions.middleware.SessionMiddleware ', ' Django.contrib.auth.middleware.AuthenticationMiddleware ' is turned on.

3. Create account: Python manage.py createsuperuser

Username (leave blank to use ' root '): Django

Email address: [Email protected]

Password:

Password (again):

Superuser created successfully. (The database tables, such as Auth, are generated when the database was last synchronized for viewing)

4, the admin access path comment in urls.py is canceled, the default is open.

5, start the development server, Access http://10.0.18.33:8002/admin/

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/8C/08/wKiom1hfawaS46oOAABYUktsBls035.png "title=" 2.png " Style= "width:700px;height:254px", "alt=" Wkiom1hfawas46ooaabyuktsbls035.png "width=" "vspace=" 0 "hspace=" 0 "Height = "254" border= "0"/>

Attach: If you want to make the interface into Chinese, add ' django.middleware.locale.LocaleMiddleware ' (this is a middleware) within the middleware of the config file, it must be placed in the ' Django.contrib.sessions.middleware.SessionMiddleware ' behind.

Registering the model Modle to the admin interface

Vim ~/helloworld/mysql_django/admin.py

From Django.contrib import admin**from mysql_django.models import Publisher, Author, Book**admin.site.register ( Publisher) #将Publisher模块注册到管理工具 **admin.site.register (Author) **admin.site.register (book)

Once done, visit again if it does not appear to restart the server, then click on the point to create the edit delete, and to understand the books module and authors's many-to-many relationship with Publisher foreign key.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/8C/08/wKiom1hfa6uATUEWAABX195lty8039.png "title=" 3.png " Style= "width:700px;height:361px", "alt=" Wkiom1hfa6uatuewaabx195lty8039.png "width=" "vspace=" 0 "hspace=" 0 "Height = "361" border= "0"/>


"Admin Management Interface Optimization"

Custom Module class display

Vim ~/helloworld/mysql_django/models.py

..... class author (Models.),... Model):     first_name = models. Charfield (max_length=30)     last_name = models. Charfield (max_length=30) **#  email = models. Emailfield (blank=true) **   email = models. Emailfield (blank=true,verbose_name= ' e-mail ') **=  email = models. Emailfield (' e-mail ',   blank=true)     def __unicode__ (self):           return u '%s %s '  %  (Self.first_name, Self.last_name) Class book (models. Model):     title = models. Charfield (max_length=50)     authors = models. Manytomanyfield (Author)     publisher = models. ForeignKey (Publisher) **   publication_date = models. Datefield (blank=true, null=true)     def __unIcode__ (self):           return self.title 

Code interpretation:

1, blank=true set field optional, by default we want to fill in each field for the form;

2, verbose_name= ' e-mail ' Set the Web Interface field label, default label first uppercase, space instead of underline.

Attach: **= is a fixed position parameter pass, etc., but not suitable for Manytomanyfield and ForeignKey fields, because their first parameter must be a module class.

3, Blank=true and Null=true set Date type (Datefield, Timefield, Datetimefield) or digital (Integerfield, Decimalfield, Floatfield) fields are optional. Adding null=true is more complex than adding blank=true. The former changes the definition of the data, that is, the CREATE table removes the NOT null on this field, so we also update the database:

Check syntax: Python manage.py check

Generate migration file: Python manage.py makemigrations Mysql_django

Synchronizing files to a database: Python manage.py migrate

Convert to SQL statement view: Python manage.py sqlmigrate Mysql_django 0003

Append: In SQL, the null value differs from the empty string, just as none in Python is different from an empty string. To eliminate ambiguity, Django defaults to NOT null for each field, and in the administrative tool you leave a string blank, which inserts an empty string (not null).

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/8C/04/wKioL1hfbIKA0nqoAACX0q2L0pI873.png "title=" 4.png " Style= "width:700px;height:357px", "alt=" Wkiol1hfbika0nqoaacx0q2l0pi873.png "width=" "vspace=" 0 "hspace=" 0 "Height = "357" border= "0"/>

These are the module-level modifications that are Modeladmin classes if special module modifications are made to the management tool level.

Custom Modeladmin class Display

The previous section of the Unicode method we defined in the author module returned shows the first_name and last_name, and we continue to improve

Vim ~/helloworld/mysql_django/admin.py

from django.contrib import adminfrom mysql_django.models import publisher,  Author, book# register your models here.**class authoradmin (admin. Modeladmin):* *    list_display =  (' first_name ',  ' last_name ',  ' email ') * *    search_fields =  (' first_name ',  ' last_name ') **class BookAdmin ( Admin. Modeladmin):* *    list_display =  (' title ',  ' publisher ',  ' Publication_ Date ') **    list_filter =  (' Publication_date ',) **    date_ hierarchy =  ' publication_date ' **    ordering =  ('-publication_date ',) * *    fields =  (' title ',  ' authors ',  ' publisher ') **     filter_horizontal =  (' authors ',) **    raw_id_fields =  (' Publisher ',) Admin.site.register (publIsher) **admin.site.register (author,authoradmin) **admin.site.register (book,bookadmin) 

Code interpretation:

1, new authoradmin and Bookadmin class, derived from Django.contrib.admin.ModelAdmin subclasses, for management tools to use;

2, List_display define the field name of the tuple, for the list display;

3, Search_fields to define the fast query bar First_name/last_name;

4, List_filter Create a date-type shortcut filter, including today, the past seven days, etc.;

5, Date_hierarchy Another time filter, display than the last intuitive;

6, ordering set by default in descending order of publication_date time;

6, Admin.site.register (Author/book) was added after Xxxxadmin. Understandable: Use the xxxadmin option to register the XXXXX module;

7, the Admin.site.register () function accepts the Modeladmin subclass as the second parameter, and no second parameter uses the default option, such as publisher;

8, fields define the form (the next chapter is fine), it hides the Publication_date field, restricts the user to change it;

9, Filter_horizontal for many-to-many fields of the more personalized choice to delete, filter_vertical and he, the same display way, see a person likes;

10, Raw_id_fields Jump new Window Select foreign key field, default is the drop-down box, but if publisher record too much, load and display in the drop-down box will be time-consuming;

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/8C/04/wKioL1hfbUuyDjzTAAFUd9vZtkw671.png "title=" 5.png " Style= "width:700px;height:285px", "alt=" Wkiol1hfbuuydjztaafud9vztkw671.png "width=" "vspace=" 0 "hspace=" 0 "Height = "285" border= "0"/>

"Analysis of the principle, purpose and authority of the admin"

How admin works

1, Django from urls.py boot urlconf, execute admin.autodiscover () statement, function traversal Installed_apps, look for admin.py file;

2, Find admin.py, Admin.site.register () Registration module, management tool for the registered display an edit/modify interface;

3. Users and groups originate from the admin.py of the application Django.contrib.auth itself.

Management interface Purpose

provided to non-technical users to enter their data.

Users, Groups, permissions

Because we are logged in with Superuser, we can create, edit, and delete any object. However, the actual environment is obviously not the case, we will explain the user rights and configuration later. First this has a set of Boolean flags:

1, the Activity flag: Control whether the user has been activated, if the status is off, even if the password is correct can not login;

2, Member flag: Control user can login management interface, distinguish the public user (edit control the public interface) and manage users (Edit Control Management page)

3, Super User flag: Give the user in the management interface all permissions, if the account has this flag, all permissions will be ignored.

Note: When creating a user, we define user rights, and permissions are defined at the module level, not the object level; For example, you can make him change any book, but he cannot modify the books that the mechanical industry publishes;

You can't assign a user permission to modify a user's permissions, or he can turn himself into a super administrator; it's better to assign users to a group and manage them easily.

---------------------------------------------------------------------------------------------------

We hope to share our progress with you. If there is any mistake, please give me a lot of advice.




This article is from the "North Ice--q" blog, please be sure to keep this source http://beibing.blog.51cto.com/10693373/1885945

Django-Admin management tool

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.