Django learning experience

高洛峰
Release: 2016-10-17 14:07:22
Original
1785 people have browsed it

Django is a python web development framework that follows the MVC design pattern, but is often called MTV (model-template-views) in Django. Model is the data persistence layer, which mainly stores entity mapping, entity relationships, and some methods of entities. Template is the presentation layer, mainly used to display data. Django's view engine can render it into HTML and display it. Views is the business logic layer, which acts as a bridge between model and template in Django. It processes the model and submits data to the template. It also accepts template requests and parameters, and submits model modifications after completing the corresponding logic.

Personally, I think MTV and .NET MVC here express the same meaning. The biggest difference is that in .net, views are the presentation layer, while in Django, it is the business logic layer. According to the official document, it is just a lack of understanding of views. It's just the same. In fact, it can be used as a controller. Below I will introduce the syntax and features of Django based on some personal understanding.

1. Views and URLs

views is the business logic layer. In Django, views are usually a views.py module, placed in the corresponding package. Views.py contains specific logical functions. Each function corresponds to one or more templates. In order to establish the connection between templates and views, a certain routing mechanism is required, so Django usually has a routing program urls.py in the root directory. . Routes are created by patterns and described by regular expressions, which greatly improves the flexibility of the routing mechanism.

For example:

views.py

def home(request):
    values = request.META.items()
    values.sort()
    return render_to_response('home.html',{"values":values})
urls.py
from django.conf.urls.defaults import *
    urlpatterns = patterns('',('^$',home),)
Copy after login


The request parameter is required here, but you can name it arbitrarily, as long as it meets the specifications. The request contains the request information of the page. sender_to_response is in django.shortcuts, so you have to declare form django.shortcuts import sender_to_response in front. request.MATE contains all request interface information and user information. shor() sorts the list from small to large. The return value means submitting a values ​​variable to the home.html template. The tuples in patterns in urls add regular guidance rules: excluding those whose original addresses match '^$', they are directed to home. Of course, this presupposes that the views.py file and urls.py are in the same folder, otherwise the home namespace must be referenced. If you want to pass multiple values ​​in the URL, you can add brackets to the matching value you want to pass, such as ('^([^/]+)/([^/]+) /$', home) to match /some/some/ and some will be passed to the processing function home. The corresponding home needs to add appropriate parameters to accept.

2. Template

Template is the place where data is displayed in Django, usually in HTML format. In the template, Django's processing logic should be written in {% %}, and the variables to be displayed should be written in { { }}middle. Django's master page can be used as any document. The premise is that you must use {% block name %}{% endblock %} to declare the block to be filled or replaced. When using it, you only need to {% extends master name%} and then call the corresponding of blocks will do.

3. Model

Configure the database in the database dictionary in setting.py. After the configuration is complete, use manage.py startapp to create the app and write python code in models to describe the entity mapping. For example:

models.py

class Publisher(models.Model):
    name = models.CharField(max_length = 30)
    website = models.URLField()
  
def __unicode__(self):
    return self.name
  
class Meta:
    ordering = ['name']
Copy after login


models is included in django.db, which encapsulates the common interface of the model class. CharField() creates varchar type data, with parameters such as max_length, blank, verbose_name, etc. Indicates the maximum length, whether it is empty, and the display name respectively. def__unicode__ provides the default display after boxing. If this function is not set, the object type will be displayed by default. class Meta specifies the default sorting field of the model. At the same time, Django also provides a foreign key setting interface. Here we take book as an example

class Book(models.Model):
     title = models.CharField(max_length = 100)
     authors = models.ManyToManyField(Author) #多对多关系
     publisher = models.ForeignKey(Publisher) #多对一关系
     publication_date = models.DateField(blank = True, null = True)
Copy after login

After the creation is completed, the path to the app package must be added to the setting.py configuration file INSTALL_APPS.

Django supports codefirst. You can use manage.py syncdb to synchronize the database. When updating the database, Django first generates sql statements and then executes them. Before execution, you can run manage.py validate to check the model, or you can run manage.py sqlall books. You can directly declare the model object to implement data insertion by using save() to save the objects.filter() search, you can call delete() on the object to delete, and you can also call delete on the model to delete in batches. In the same way, update calls a single modification on the object and a batch modification on the model.

4. Integrated sub-framework

There are a variety of additional function packages in the django.contrib package. Currently, we only know about admin and auth, which feel very powerful. The only drawback is that the admin interface is slightly ugly. Admin is the backend management platform officially provided by Django. It can manage the apps you added and integrates all common functions including adding, deleting, modifying and checking. The calling code is also very simple. You only need to activate the admin link in urls.py. The configuration file is in setting.py. You can change it yourself if necessary. If you want to add app management, you need to add the following code (take Book as an example):

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'publisher', 'publication_date') #显示顺序
    list_filter = ('publication_date',) #过滤列表
    ate_hierarchy = 'publication_date' #激活列表上方的日期查询
    ordering = ('-publication_date',) #排序方式'-'代表倒序
    filter_horizontal = ('authors',) #添加时候的横向选择过滤(此处假设book和authors 是多对多关系)
    raw_id_fields = ('publisher',) #添加时候的选择(此处假设publisher和book是一对多关系)
  
admin.site.register(Publisher)
admin.site.register(Author,AuthorAdmin)
admin.site.register(Book,BookAdmin)
Copy after login


5. Caching mechanism

Personally, I think caching is very important for a website with too many visits. , the caching methods provided in Django are roughly divided into three types: full-site cache configuration method, view cache configuration method, and data cache configuration method. Just modify the relevant configuration files. You can also install other plug-ins to assist caching, such as memcached.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template