Django (novice bird course)

Keywords: Django Database Python pip

Learn the Django tutorial of the novice bird tutorial, link as follows:

http://www.runoob.com/django/django-tutorial.html


Installation:

pip install Django

If PIP < 1.4, use:

pip install https://www.djangoproject.com/download/1.11a1/tarball/

Or clone code:

git clone https://github.com/django/django.git


Create a project:

django-admin.py startproject HelloWorld


Create an app in the project:

django-admin.py startapp TestModel


Start the server method:

python manager.py runserver 0.0.0.0:8000


Access Method: Browser Input

localhost:8000/


django uses mvc structure, creates templates directory under the project root directory, and modifies settings.py under the main project (see # Modify Location section):

...TEMPLATES = [

    {

       'BACKEND': 'django.template.backends.django.DjangoTemplates',

       'DIRS': [BASE_DIR+"/templates",],       #modify location

       'APP_DIRS': True,

       'OPTIONS': {

           'context_processors': [

               'django.template.context_processors.debug',

               'django.template.context_processors.request',

               'django.contrib.auth.context_processors.auth',

                'django.contrib.messages.context_processors.messages',

           ],

       },

   },

]

...

In this way, html files can be placed in templates and rendered by render.


Mapping rules:

Modify the urls.py file under the main project, where the path accessed by the browser is mapped to a specific class for processing, such as:

urlpatterns = [

   url(r'^hello$', view.hello),

]

Here view is py file, hello is one of the functions used to process the response to *. *. *: 8000/hello format. Its main function is to render the template file as a response value, such as:

from django.shortcuts import render


def hello(request):

   context          = {}

   context['hello'] = 'Hello World!'

   return render(request, 'hello.html', context)

hello.html is a file placed in templates, and the content in context is passed to hello.html as a variable.

In template files, variables and control logic can be used.

In variable mode, it is {xxx}, for example, the parameter passed above will be used in hello.html: {hello}}

The format of control logic is

 {% if xxx % }  xxx  {% endif %} 

Or

{% for %} xxx  {% endfor%} 

etc.

The format of the annotation is

{# xxx #}

It can also inherit:

Setting inheritance in base.html

{% block name %} xxx {% endblock %}

Then the sub.html declaration in the subclass:

{% extends "base.html" %}

Then modify the inherited segment

 {% block name %} xxx {%endblock %}

It may also include:

{% include"xxx.html" %}


The above hello processing can distinguish between GET processing and POST processing:

if request.method == 'GET':

   do_something()

elif request.method == 'POST':

   do_something_else()

The parameters can be obtained directly from the parameter dictionary, such as:

request.POST['q']

Here'q'is the parameter, which is used as the index value to get the corresponding parameters.

For example, the processing of form submission is as follows:

# Receiving POST request data

def search_post(request):

   ctx ={}

   if request.POST:

       ctx['rlt'] = request.POST['q']

   return render(request, "post.html", ctx)

In the process of response function, it can also interact with database.

First configure the database: (you can also configure mysql)

DATABASES = {

   'default': {

       'ENGINE': 'django.db.backends.sqlite3',

       'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

       'USER': 'Jacob',

       'PASSWORD': '123456',

       'HOST': 'localhost',

       'PORT': '3306',

    }

}

Create an app for the database and add the name of the app to the INSTALLED_APPS entry of settings.py.

Then you can define tables, such as:

# models.py

from django.db import models


class Test(models.Model):

   name = models.CharField(max_length=20)

Then let the database create the table: (the following command is not less than one)

python manage.py migrate   #Create a table structure

python manage.py makemigrationsTestModel  #Let Django know that we have some changes in our model

python manage.py migrate TestModel   #Create a table structure

By manipulating the database content, you can use the above classes, such as generating an entry:

test = Test(name='vvv')

test.save()

Delete an entry:

Test.objects.filter(id=1).delete()

Update an entry:

Test.objects.filter(id=1).update(name='Google')

Full update:

Test.objects.all().update(name='all')

After writing the database operation code, remember to modify the admin.py file in the database app directory:

from django.contrib import admin

from TestModel.models import Test


# Register your models here.

admin.site.register(Test)

Here admin, in fact, is a management page provided by django, which can easily display the database information.


Then, admin is introduced in detail.

First, activate the management tool by modifying the mapping rule file urls.py and adding entries to urlpatterns:

url(r'^admin/', admin.site.urls),

Create a superuser:

python manage.py createsuperuser

In this way, it can be accessed in the browser through localhost:8000/admin/.

In the page, you can see the relevant databases you created earlier and manipulate their contents.

At the same time, you can customize the forms displayed in the database, such as defining a Contact database:

class Contact(models.Model):

   name   = models.CharField(max_length=200)

   age    =models.IntegerField(default=0)

   email  = models.EmailField()

   def __unicode__(self):

       return self.name

When registering in admin.py, customize the form as follows:

# Register your models here.

class ContactAdmin(admin.ModelAdmin):

   fields = ('name', 'email')


admin.site.register(Contact, ContactAdmin)

You can also do list style, inline other data tables, add search bar, etc. Examples are as follows:

# Register your models here.

class TagInline(admin.TabularInline):

   model = Tag

class ContactAdmin(admin.ModelAdmin):

   list_display = ('name','age', 'email') # list

   search_fields = ('name',)

   inlines = [TagInline]  # Inline

   fieldsets = (

       ['Main',{

           'fields':('name','email'),

       }],

       ['Advance',{

           'classes': ('collapse',),

           'fields': ('age',),

       }]

    )

admin.site.register(Contact, ContactAdmin)


Complete Code Engineering See:

https://pan.baidu.com/s/1mjfS4Ak Password: dk6n

Posted by plisken on Fri, 17 May 2019 12:22:11 -0700