Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Template Model of python_Django

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Main document

Manage.py create server

Configuration information for settings.py project

Urls.py URL dispenser (mapping table of URLconf----URL and function)

View.py view (function)

Manage.py

Start manage.py to create a simple server for debugging

Python manage.py runserver 0.0.0.0:8000

Urls.py

Patterns: the first is an empty string (explained later)

Include:

Urls:

From django.conf.urls.defaults import patterns, include, urlfrom mysite.views import hello # are usually views. Call urlpatterns = patterns ('', url (r'^ hello/$', hello),)

What happens if someone requests access to / hello (there is no slash at the tail /). Because our URL pattern requires a slash (/) at the end, that application URL will not match. However, by default, any application URL that does not match or does not have a slash (/) in the tail will be redirected to a URL with the same word containing the slash in the tail. (this is controlled by the APPEND_SLASH entry in the configuration file setting

Url (r'^ articles/ ([0-9] {4}) / ([0-9] {2}) / ([0-9] +) / $', views.article_detail)

The contents in these three parentheses are passed to the function as the second, third and fourth arguments. The first parameter is request.

View.py

A view is a function of Python. The first argument to this function is of type HttpRequest;, which returns an instance of HttpResponse.

Request is an object that triggers this view and contains the current Web request information, and is an instance of the class django.http.HttpRequest.

From django.http import HttpResponsedef hello (request): return HttpResponse ("Hello world") # returns the string directly-from django.shortcuts import renderdef be_001 (request): return render (request) '001.html') # returns the 001.html under the template file

Settings.py

Set the specified URLconf (url dispenser)

ROOT_URLCONF = 'mysite.urls' # that is, the request from mysite/urls.py is transferred to / hello/.

Django determines the root URLconf. URLconf by configuring it in ROOT_URLCONF.

Django looks for the first entry that matches / hello/ in all URL schemas in URLconf.

If a match is found, the corresponding view function is called and the HttpRequest object is taken as the first parameter

The view function returns a HttpResponse

Django converts HttpResponse to a suitable HTTP response, which is displayed in Web page

Specify the template path

TEMPLATE_DIRS = (os.path.join (os.path.dirname (_ file__), 'templates'). Replace ('\','/'), # automatically gets the path of settings.py and splices to get the template path) # A comma must be used in a single element tuple to eliminate ambiguity with parenthesis expressions.

Template

Enter the command python manage.py shell in the project directory (django-admin.py startproject) to start the interactive interface (the relevant configuration will be loaded automatically)

Circular judgment

{% for item in item_list%} # represents an integer counter for the number of times the current loop is executed. This counter starts at 1 and forloop.counter0 starts at zero.

`forloop`.`counter `: `item`

# forloop.revcounter is an integer variable that represents the rest of the loop, forloop.revcounter0

{% endfor%} # forloop.first is a Boolean and is set to true,forloop.last if the iteration is executed for the first time

# forloop.parentloop is a reference to the forloop object of the loop one level above the current loop (in the case of nested loops)

{% if ordered_warranty%} # can only use one logical operator, and or or, which cannot be used together

{% else%}

{% endif%}

{% ifequal user currentuser%} # judge whether user currentuser is equal, string should be "", can only judge whether two variables are equal

Welcome # cannot be used to determine whether a variable is equal to anything, True {op:123} [1 op:123 2], etc.

{% endifequal%}

Variable assignment

{{person_name}} is called a variable. This means inserting the value of the specified variable here.

> from django import template # Template can use render method to pass Context parameters > t = template.Template ('My name is {{name}.') > c = template.Context ({'name':' Adrian'}) > print t.render (c) My name is Adrian. > > c = template.Context ({'name':' Fred'}) > print t.render (c) # returns Unicode r''My name is Fred.

The basic rules of the Django template system: write templates, create Template objects, create Context, and call the render () method.

> > from django.template import Template, Context > import datetime > person = {'name':' Sally', 'age':' 43'}} > > t = Template ('{{person.name}} is {{person.age}} years old.') > c = Context ({'person': person}) > t.render (c) u'Sally is 43 years old.' > > d = datetime.date (1993, 5) 2) # time can also be used in this way > d.year1993 > t = Template ('Item 2 is {{items.2}}.') # list index (cannot use negative numbers) > c = Context ({'items': [' apples', 'bananas',' carrots']}) # the method is called without parentheses and parameters cannot be passed to the method > t = Template ('{var}}-- {{var.upper}}-- {{var.isdigit}}') # var variable, call upper and isdigit methods > t.render (Context ({'var':' hello'})) u'hello-HELLO-False' dictionary type lookup (such as foo ["bar"])

Attribute lookup (such as foo.bar)

Method calls (such as foo.bar ())

List type index lookup (such as foo [bar])

The system uses the first valid type found. This is a kind of short circuit logic.

A variable does not exist, the template system will display it as an empty string and do nothing to indicate failure.

Method call

Throw an exception

During method lookup, if a method throws an exception, it will be propagated (error reported).

If the exception has a silent_variable_failure attribute and the value is True, the specified variable in the template will be set to an empty string (no error will be reported)

Avoid misoperation of key functions in the template

Def delete (self):

# Delete the account

Delete.alters_data = True

# think of delete as an object and set its alters_data property. In this way, when rendering, it becomes failed silent. Will not be executed.

Annotation

Single line

{# This is a comment #}

Multiple Lin

{% comment%} This is amulti-line comment. {% endcomment%} filter

Several commonly used ones

A template filter is an easy way to change the value of a variable before it is displayed.

{{my_list | first | upper}} {{bio | truncatewords: "30"}} addslashes: add a backslash before any backslash, single or double quotation marks. This is very useful when working with text that contains JavaScript.

Date: formats date or datetime objects with specified format string parameters, example:

{{pub_date | date: "F j, Y"} format parameters are defined in Appendix F.

Length: returns the length of the variable. For a list, this parameter returns the number of elements in the list. For a string, this parameter returns the number of characters in the string. You can use this method on lists or strings, or on any Python object that knows how to measure its length (that is, an object with a _ _ len__ () method)

Detailed https://www.douban.com/note/145065606/

Template loading

Settings.py

Import os.pathTEMPLATE_DIRS = (os.path.join (os.path.dirname (_ _ file__), 'templates'). Replace ('\','/'),)

In the view

From django.template.loader import get_templatefrom django.template import Contextfrom django.http import HttpResponseimport datetimedef current_datetime (request): now = datetime.datetime.now () t = get_template ('current_datetime.html') html = t.render (Context ({' current_date': now})) return HttpResponse (html)

A more concise view

From django.shortcuts import render_to_responseimport datetimedef current_datetime (request): now = datetime.datetime.now () return render_to_response ('current_datetime.html', {' current_date': now}) # returns the HttpResponse object; # the first parameter must be the name of the template to be used The second parameter, then it must be the dictionary used to create the Context for the template. The default is the empty dictionary locals () technique def current_datetime (request): now = datetime.datetime.now () # extra variable name. Return render_to_response ('current_datetime.html', {' current_date': now}) def current_datetime (request): current_date = datetime.datetime.now () # the variable name and the consistent return render_to_response ('current_datetime.html', locals ()) # locals () in the template contain all the variables defined when the function executes to that point in time. Get_template ()-template subdirectory t = get_template ('dateapp/current_datetime.html') return render_to_response (' dateapp/current_datetime.html', {'current_date': now}) include template tags (clunky nested web pages) {% include template_name%}

If the template specified by the {% include%} tag is not found, Django will choose one of the following two processing methods:

If DEBUG is set to True, you will see a TemplateDoesNotExist exception on the Django error message page.

If DEBUG is set to False, the tag does not raise an error message and nothing is displayed at the label location.

Template inheritance (more elegant strategy) # base.html {% block title%} {% endblock%} My helpful timestamp site > > Model (model)-> View (view)

MTV

"C is handled by the framework itself (URLconf)"-> Model (Model)-> View (Views)-> template (Template)

APP

Rationalize project and app: a project contains multiple app and provides the relevant configuration for app, but the model must be in their respective app

Python manage.py startapp books # create APP

Describe the database in models.py

From django.db import modelsclass Publisher (models.Model): name = models.CharField (max_length=30) address = models.CharField (max_length=50) city = models.CharField (max_length=60) state_province = models.CharField (max_length=30) country = models.CharField (max_length=50) website = models.URLField () class Author (models.Model): first_name = models.CharField (max_length=30) last_name = models.CharField (max_length=40) Email = models.EmailField () class Book (models.Model): title = models.CharField (max_length=100) authors = models.ManyToManyField (Author) publisher = models.ForeignKey (Publisher) publication_date = models.DateField ()

The effect is the same as the following sql

CREATE TABLE "books_publisher" ("id" serial NOT NULL PRIMARY KEY, "name" varchar (30) NOT NULL, "address" varchar (50) NOT NULL, "city" varchar (60) NOT NULL, "state_province" varchar (30) NOT NULL, "country" varchar (50) NOT NULL, "website" varchar (50) NOT NULL)

Settings.py activates app

MIDDLEWARE_CLASSES = (# comments later explain # 'django.middleware.common.CommonMiddleware', #' django.contrib.sessions.middleware.SessionMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware',) INSTALLED_APPS = (#' django.contrib.auth', # 'django.contrib.contenttypes', #' django.contrib.sessions' # 'django.contrib.sites',' mysite.books',)

Check the syntax and logic of the above model (normal return 0 erros found)

Python manage.py validate generates CREATE TABLE statements

Python manage.py sqlall books

Submit to the database client for execution

Python manage.py syncdb # this command cannot be used to modify and delete

Basic data access

Python manage.py shell

> from books.models import Publisher # Import Publisher model classes to interact with data tables > p1 = Publisher (name='Apress', address='2855 Telegraph Avenue',... City='Berkeley', state_province='CA', country='U.S.A.',... Website=' http://www.apress.com/')>>> p1.save () > > p2 = Publisher (name= "O'Reilly", address='10 Fawcett St.',...) City='Cambridge', state_province='MA', country='U.S.A.',... Website=' http://www.oreilly.com/')>>> p2.save () > > publisher_list = Publisher.objects.all () > publisher_list [,]

The following does not need save, directly complete the object creation and storage to the database

> p1 = Publisher.objects.create (name='Apress',... Address='2855 Telegraph Avenue',... City='Berkeley', state_province='CA', country='U.S.A.',... Website=' http://www.apress.com/')

It is convenient to rewrite _ _ unicode__,

Class Author (models.Model): * * def _ _ unicode__ (self): * * # _ _ unicode__ () method can do any processing to return a string representation of an object * * return uplink% s% s'% (self.first_name, self.last_name) * * # must return Unicode, and something like a number will report an error

Insert update

> p = Publisher (name='Apress',... Address='2855 Telegraph Ave.',... City='Berkeley',... State_province='CA',... Country='U.S.A.',... Website=' http://www.apress.com/')>>> p.save () # is equivalent to executing INSERT INTO books_publisher*** to assign the primary key to the instance object p > p.id52 # this will differ based on your own data > p.name = 'Apress Publishing' # updatable data based on this object > p.save () # does not update only the modified field All fields will be updated. # We'll talk about it later in the partial update

Query

> Publisher.objects.all () [,] # minus sign-reverse prefix sort. The second field will be used in class Publisher (models.Model) if the value of the first field is the same: * * class Meta:** ordering = ['name'] * * in the model class (if default sorting is required), set the default sorting method, as described above when you use Django's database API to retrieve # the relevant return values of Publisher objects are sorted by name field by default

Chain query

> Publisher.objects.filter (country= "U.S.A.") .order_by ("- name") [

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report