Basic methods for managing sites in Python's Django framework

Source: Internet
Author: User
The management interface is a very important part of the infrastructure for a particular type of website. This is a Web-based interface with a limited number of trusted managers, which allows you to add, edit and delete site content. Some common examples: You can use this interface to publish a blog, the background of the site managers use it to polish the content of the reader, your customers with the interface tools you set up for them to update the news and posted on the site, these are the use of management interface examples.

But the management interface has a problem: creating it is too cumbersome. Web development is interesting when you develop functionality for the public, but the creation of a management interface is often stereotyped. You have to authenticate users, display and manage tables, validate input validity, and so on. It's tedious and repetitive.

What improvements have Django made to these tedious and repetitive tasks? It does everything for you with no less code. It is no longer a problem to create a management interface in Django.

This chapter is about Django's automatic management interface. This feature works: it reads the metadata in your schema and provides you with a powerful and accessible interface that the site manager can use to work immediately.

Please note that we recommend that you read this chapter even if you do not intend to use admin. Because we're going to introduce a few concepts that can be applied to all aspects of Django, not just the admin
Django.contrib Bag

The Django Automatic management tool is part of the Django.contrib. Django.contrib is a huge set of features that are part of the Django CodeBase, and the Django framework consists of a number of basic code that contains add-ons (add-on). You can think of django.contrib as a practical implementation of the optional Python standard library or universal schema. They are bundled with Django so you don't have to "reinvent the wheel" in development.

The management tool is the first part of this book that tells Django.contrib. Technically speaking, it is called django.contrib.admin. Other features available in Django.contrib such as user identification System (DJANGO.CONTRIB.AUTH), anonymous session support (Django.contrib.sessioins), and user commentary system ( django.contrib.comments). These, we will discuss in detail in the 16th chapter. Before you become a Django expert, you will know more about the features of Django.contrib. For now, you just need to know that Django comes with a lot of good add-ons, all of them in the Django.contrib package.
Activating the Management interface

The Django administration site is completely optional, because only certain special types of sites require these features. This means that you need to spend a few steps in your project to activate it.

The first step is to make the following changes to your settings file:

Adding ' django.contrib.admin ' to Setting's Installed_apps configuration (the order of configuration in Installed_apps is not related, but we prefer to keep it in a certain order for people to read)

Ensure that the Installed_apps contains ' Django.contrib.auth ', ' django.contrib.contenttypes ' and ' django.contrib.sessions ', The Django management tool requires these 3 packages. (If you follow this article to make the MySite project, then please note that we have commented on these three Installed_apps entries in the fifth chapter.) Now, please cancel the comment. )

Make sure middleware_classes contains ' django.middleware.common.CommonMiddleware ', ' Django.contrib.sessions.middleware.SessionMiddleware ' and ' Django.contrib.auth.middleware.AuthenticationMiddleware ' 。 (Again, if there is a follow-up mysite, please cancel the comments made in Chapter fifth.) )

Run Python manage.py syncdb. This step will generate additional database tables used by the management interface. When you add ' Django.contrib.auth ' to Installed_apps, the first time you run the SYNCDB command, the system will ask you to create a superuser. If you do not, you need to run Python manage.py createsuperuser to create another Admin user account, otherwise you will not be able to login admin (warning: only if Installed_apps contains ' Django. Contrib.auth ', python manage.py createsuperuser This command is available.)

Third, the admin access is configured in Urlconf (remember, in urls.py). By default, the command django-admin.py startproject the generated file urls.py is to comment out the Django Admin path, all you have to do is uncomment. Please note that the following must be ensured:

# include these import statements...from Django.contrib import Adminadmin.autodiscover () # and include this urlpattern...u Rlpatterns = Patterns ("', # ... (R ' ^admin/', include (Admin.site.urls)), # ...)

When this is all configured, you will now find that the Django management tool is ready to run. Start the development server (ex: ' Python manage.py runserver ') and then access it in the browser: http://127.0.0.1:8000/admin/

Add your models to admin management

There is a critical step we haven't done yet. Let's add our own modules to the management tool so that we can use this nice interface for adding, modifying, and deleting objects in the database.
In this, we define three modules: Publisher, Author, and book.

In the ' Books ' Directory (' Mysite/books '), create a file: ' admin.py ' and enter the following code:

From Django.contrib import adminfrom mysite.books.models Import publisher, Author, Bookadmin.site.register (publisher) Admin.site.register (Author) admin.site.register (book)

The code notifies the management tool to provide the interface for each of these modules.

When you're done, open the page ' http://127.0.0.1:8000/admin/' and you'll see a books area that contains authors, books, and publishers. (You may need to stop and then start the service ("Runserver") before it can take effect. )

Now you have a full-featured management interface to manage these three modules. It's simple!

Take some time to add and modify records to populate the database. If you create a Publisher object with the example of the fifth chapter (and you don't delete it), you'll see those records in the list.

One feature that needs to be mentioned here is that the management tool handles foreign keys and many-to-many relationships (both of which can be found in the ' book ' module). As a reminder, here's an example of a ' book ' module:

Class book (Models. Model):  title = models. Charfield (max_length=100)  authors = models. Manytomanyfield (Author)  publisher = models. ForeignKey (Publisher)  publication_date = models. Datefield ()  def __unicode__ (self):    return Self.title

In the Add Book page (' http://127.0.0.1:8000/admin/books/book/add/'), ' foreign key ' publisher uses a selection box to display the ' many-to-many ' field author with a multi-box display. Clicking the green plus sign after two fields allows you to add related records. For example, if you click the plus sign behind publisher, you'll get a pop-up window to add a publisher. When you successfully create a Publisher in that window, the Add book form automatically updates it to the field.

  • 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.