Django Foundation (i), project creation, URL routing, database operations

Source: Internet
Author: User
Tags install django

First, install Django


: https://www.djangoproject.com/download/


1. Tar zxvf django-1.8.10.tar.gz

2. CD Django-1.8.10

3. Python setup.py Install


Second, create a Django project


Django-admin Startproject SiteName


Common commands:

Python manage.py runserver 0.0.0.0
Python manage.py Startapp AppName
Python manage.py syncdb
Python manage.py makemigrations
Python manage.py Migrate


Third, URL routing


1. Each routing rule corresponds to a function in the view

From Django.conf.urls import include, Urlfrom django.contrib import adminfrom views Import *urlpatterns = [url (' ^hello /$ ', hello), url (' ^time/$ ', current_datetime), url (r ' ^time/plus/(\d{1,2})/$ ', Hours_ahead),]


2, according to the app corresponding routing rules classification

URL (r ' ^web1/', include (' Web1.urls '))


App:web1.urls

From django.conf.urls import include, URL, patternsfrom django.contrib import adminfrom web1.views import *urlpatterns = P Atterns (",", url (r ' ^add/(? p<name>\w*) & (? p<not_name>\w*)/$ ', Add), url (r ' ^del/(? p<id>\d*)/$ ', Delete), url (r ' ^update/(? p<id>\d*) & (? p<name>\w*) (/$ ', Update),)


Iv. Database Operations


1. Configuration:

DATABASES = {' Default ': ' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' dbname ', ' USER ': ' Root ', ' PASSWORD ': ' xxx ', ' HOST ': ', ' PORT ': ',}}


2, according to models. Model Create data table

#!/usr/local/python27/bin/python2.7# Coding:utf8 # Create Your models here.from django.db import Modelsclass UserInfo2 (M Odels. Model): Username = models. Charfield (max_length=50) password = models. Charfield (max_length=50) memo = models. Charfield (MAX_LENGTH=50) class args (models. Model): id = models. Autofield (Primary_key = True) name = models. Charfield (max_length=20,null=true) Not_name = models. Charfield (max_length=20,null=false) Create_data = models. Datetimefield (Auto_now_add = True) Update_date = models. Datetimefield (Auto_now = true,error_messages={"Invalid": ' Date format error '})


3 , more fields:

1, models. Autofield self-increment  = int (11) If not, the default is to generate a column named  id , and if you want to display a custom self-increment column, you must set the column as the primary key  primary_key= True. 2, models. Charfield string field must be  max_length  parameter 3, models. Booleanfield Boolean type =tinyint (1) cannot be empty, blank=true4, models. Comaseparatedintegerfield with a comma-separated number =varchar inherit Charfield, so must  max_lenght  parameter 5, models. Datefield Date type  date for parameter,auto_now = true  each update will update this time;auto_now_add  it is just the first time you create the Add, Subsequent updates will no longer change. 6, models. Datetimefield Date type  datetime with Datefield parameter 7, models. Decimal decimal Decimals Type  = decimal must specify an integer digit max_digits and a decimal bit decimal_places8, models. Emailfield String type (regular expression mailbox)  =varchar Regular Expression 9, models for strings. Floatfield floating-point type  = double10, models. Integerfield Plastic 11, models. Bigintegerfield long plastic integer_field_ranges = {' Smallintegerfield ':  ( -32768, 32767), ' IntegerFie LD ':  ( -2147483648, 2147483647), ' Bigintegerfield ':  ( -9223372036854775808,  9223372036854775807), ' PositivesmallintegerField ':  (0, 32767), ' Positiveintegerfield ':  (0, 2147483647),}12, models. Ipaddressfield String type (IP4 regular expression) 13, models. Genericipaddressfield String Types (IP4 and IP6 are optional) parameters protocol can be: both, IPv4, IPv6 validation, according to the set error 14, models. Nullbooleanfield is allowed to be null for Boolean type 15, models. Positiveintegerfiel is Integer16, models. Positivesmallintegerfield is SmallInteger17, models. Slugfield minus, underscore, letter, number 18, models. The fields in the Smallintegerfield digital database are: tinyint, smallint, int, bigint19, models. TextField string =longtext20, models. Timefield time  hh:mm[:ss[.uuuuuu]]21, models. Urlfield string, address regular expression 22, models. Binaryfield binary <br>23, models. imagefield    pictures <br>24, models. filepathfield  file


4. More Field Parameters:

1, whether the field in the Null=true database can be empty 2, Blank=true Django Admin to add data when you can allow null value 3, Primary_key = False primary key, after the Autofield set the primary key, will replace the original self-increment ID column        4, Auto_now and Auto_now_add Auto_now automatically created---whether added or modified, is the time of the current operation Auto_now_add automatically created---is always created at the time of 5, Choicesgender_choice = ( (U ' M ', U ' Male '), (U ' F ', U ' Female '),) gender = models. Charfield (max_length=2,choices = gender_choice) 6, Max_length7, default value 8, verbose_name admin field display name 9, name|db_ Field name in column database 10, unique=true not allowed to repeat 11, Db_index = True Database index 12, editable=true in admin can edit 13, error_messages=none error prompt 1 4, Auto_created=false automatically create 15, Help_text in admin tips help information 16, validators=[]17, upload-to


from django.shortcuts import renderfrom web1.models import *from  django.http import httpresponsefrom django.db.models import min,max,sumfrom  django.db import connection,transaction# create your views here.#  Adding Data def  add (request,name,not_name):     args.objects.create (Not_name=not_name,name=name)     return httpresponse (' OK ') #  delete data def delete (request,id):     args.objects.get (id=id). Delete ()     return httpresponse (' Delete ok ') #  update data, single-line update         def update (request,id,name):            obj = args.objects.get (Id=id)      obj.name = name    obj.save ()     return  HttpResponse (' Update ok ')     #  Multiple lines Update     args.objects.filter (ID__GT=ID) based on a condition with an ID greater than equals. Update (Name=name)       return httpresponse (' Multi update ok ') #  based on a condition with an ID less than equals, multiple rows of updates, or can be used for multiple row deletions     args.objects.filter (id__lt=id). Update (Name=name)     return  HttpResponse (' Multi update ok ') #  operation based on equal conditions         Args.objects.filter (id=id). Update (Name=name)     return httpresponse (' multi  Update ok ')          #还可以通过filter (id__in = [1,2,3]) for multi-line operation      #  Fuzzy query Def get (request,name):    obj =  Args.objects.filter (Name__contains=name)     l1 = []    for  i in obj:        l1.append (I.name)          l1. append (' \ n ')     return httpresponse (L1)     #  get all data, Gets a single column of data through the values () specification. Def get_all (Request):     alldata = args.objects.all (). VALUES (' ID ')      print alldata.query    return httpresponse (ALLDATA) #  Gets the specified row data,[0:3]  3 rows of data starting from 0 rows def get_limit (Request):    alldata =  Args.objects.all () [0:3]    print alldata.query    return  HttpResponse (alldata) #  sort  , ('-id ') is in reverse order     alldata = args.objects.all (). order_by (' id ')       alldata = args.objects.all (). order_by ('-id ') #   Aggregate function Def juhe (Request):     alldata = args.objects.aggregate (Max (' id '))     print alldata    return httpresponse (ALLDATA) #  Use a custom native SQL statement "' cursor&Nbsp;= connection.cursor () cursor.execute (' Select distinct first_name rom people_ person where last_name = %s ',  [' Lennon ']) Row = cursor.fetchone ()   "#   Example: Def sour_sql (request,id):     cursor = connection.cursor ()      cursor.execute ("' select id from web1_args where id >  %s  " % id )     row = cursor.fetchall ()      print row    return httpresponse (Row)





This article is from the "Break Comfort zone" blog, so be sure to keep this source http://tchuairen.blog.51cto.com/3848118/1750478

Django Foundation (i), project creation, URL routing, database operations

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.