The learning process of Django over the past few days is quite pleasant. Django adopts the MVC Architecture, and the learning curve is very gentle. Before learning deeply, first, record the methods that Django uses in the template to obtain data from the database. Zhixin zhi_^
First, let's assume a simple scenario where the database stores the author's and book's target information. This is a multi-to-many structure, because one author can write multiple books and one book may be completed by multiple authors. How can we use Django to create projects, configure databases, create views, templates, configure URL routes, and finally access the pages we dynamically create in a browser,
The following part is counted as a record and will briefly describe how Django works. If you are a newbie, you may gain some insights and have a rough understanding of Django. I recommend you read "Django book (Chinese version)" as a friend who wants to systematically learn Django. This document has been around for a few years. However, the principle and basic operations have not changed recently, that is, the directory structure changes with the version upgrade, which has no major impact. For example, you can see the Django official documentation, which is of course the best.
Assume that you have configured the Django environment. Run the following command to create a project:
django-admin.py startproject projectcd projectpython mamages.py startapp blog
In this way, a basic project is created. ComeTreeTake a look:
[[email protected] project]# tree
Display result:
.├── blog│ ├── admin.py│ ├── __init__.py│ ├── migrations│ │ └── __init__.py│ ├── models.py│ ├── tests.py│ └── views.py├── manage.py└── project ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py 3 directories, 11 files
The file to be modified is settings. py. register the newly created app and configure the MySQL database. Find
INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘blog‘)
Add an app and configure the database, name, user, and password as follows.
DATABASES = { ‘default‘: { ‘ENGINE‘: ‘django.db.backends.mysql‘, #‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘), ‘NAME‘: ‘AuthBooks‘, ‘USER‘: ‘root‘, ‘PASSWORD‘: ‘123456‘, }}
Next, configure the URL route and modify URLs. py. This function is to match the URL and submit it to views. py for processing.
from django.conf.urls import patterns, include, urlfrom django.contrib import admin urlpatterns = patterns(‘‘, # Examples: # url(r‘^$‘, ‘project.views.home‘, name=‘home‘), # url(r‘^blog/‘, include(‘blog.urls‘)), url(r‘^admin/‘, include(admin.site.urls)), url(r‘^author/$‘, ‘blog.views.show_author‘), url(r‘^book/$‘, ‘blog.views.show_book‘),)
In this way, our URLs such as 127.0.0.1/author and 127.0.0.1/book will enter different processing functions to process them. Next we will compile views. py to implement the corresponding functions. Before that, we must first understand the database and how to create data, initialize tables, and obtain data. So that we can continue. In the models. py module, we define the following tables: Author, book, author, and author, and book, respectively.
from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Book(models.Model): name = models.CharField(max_length=30) authors = models.ManyToManyField(Author) def __unicode__(self): return self.name
Next, we need to initialize the database. Run the following command.
python manage.py syncdb
Operations to perform:Apply all migrations: admin, contenttypes, auth, sessionsRunning migrations:Applying contenttypes.0001_initial… OKApplying auth.0001_initial… OKApplying admin.0001_initial… OKApplying sessions.0001_initial… OKYou have installed Django’s auth system, and don’t have any superusers defined.Would you like to create one now? (yes/no):
Here we will ask if we have created a management account. Select Yes and follow the prompts to complete the creation. Go to the project root directory to see if there is a database named dB. sqlite3 ~
Next, we will use the shell exercises provided by the project to add author, books, and other data. And then process it in the Views. py module.
python manage.py shell
In this way, we enter a shell environment that Django has configured for us. We can easily import related modules without worrying about the not found issue.
Next, run the following commands. To add records for the database
from blog.models import Author, BookAuthor.objects.create(name=‘sin‘)Author.objects.create(name=‘sun‘)Author.objects.create(name=‘lin‘)b1 = Book()b1.name = ‘book1‘b1.save()b2 = Book()b2.name = ‘book2‘b2.save()b3 = Book()b3.name = ‘book3‘b3.save()sin = Author.objects.get(name__exact=‘sin‘)sun = Author.objects.get(name__exact=‘sun‘)lin = Author.objects.get(name__exact=‘lin‘)b1.authors.add(sin)b1.authors.add(sun)b2.authors.add(sun)b3.authors.add(sun)b3.authors.add(lin)
You can establish the authors-books correspondence as shown in the preceding command.
Add some common commands
(Query the author by Book)
Query the corresponding
>>> b1.authors.all()[<Author: sin>, <Author: sun>]>>> b2.authors.all()[<Author: sun>]>>> b3.authors.all()[<Author: sun>, <Author: lin>]
Query specified authors in the book to see if they exist
b1.authors.filter(name__exact=‘sin‘)
Delete a book
b1.authors.remove(sun)
(Query his books based on the author)
>>> sin.book_set.all()[<Book: book1>]>>> sun.book_set.all()[<Book: book1>, <Book: book2>, <Book: book3>]>>> lin.book_set.all()[<Book: book3>]
In fact, book_set is equivalent to the previous objects
>>> sin.book_set.add(b3)>>> sin.book_set.remove(b3)>>> sin.book_set.all()[<Book: book1>]
Add a new Bibliography for the author:
sin.book_set.create(name=‘book4‘)
The above commands are encapsulated database operation commands, and all the changes made will be saved in the database. Next, you can configure view. py and compile the template to visually display the correspondence between the author and the book in HTML.
View. py contains the following content, which is used to process what the corresponding URL has done. Here, a template that has been processed is returned.
from django.shortcuts import render_to_responsefrom blog.models import Author, Book # Create your views here. def show_author(request): authors = Author.objects.all() return render_to_response(‘show_author.html‘, {‘authors‘:authors}) def show_book(request): books = Book.objects.all() return render_to_response(‘show_book.html‘, {‘books‘:books})
Create a new templatesfolder in the blogobject directory. This is the template search page of the system. The newly created show_author.html file is as follows:
{% for author in authors %} <div>
Create show_book.html again with the following content:
{% for book in books %}
OK. The preceding figure shows how to create an app, configure the database, add data, configure the URL routing, write the view, and all the content of the template.
Run our project and access it on the browser.
Run the following command in the project directory:
python manage.py runserver
In this way, you can see the effect locally through 127.0.0.1: 8000/author and 127.0.0.1: 8000/book.
If you are using a Virtual Machine (bridging the Internet), you can use the following command
python manage.py runserver 0.0.0.0:80
You can use the IP address of your VM to access the service. (You may need to use iptables-F to temporarily disable iptables)
Okay. Let's see if it's the same as my running results ~
After finishing, continue to the next step.
Django example-template rendering of model data