Pycharmimplementation (Django's model, forms, management tools, introduction of static files)

1, Django model (PyCharm Implementation)

Django provides good support for various databases, including PostgreSQL, MySQL, SQLite and Oracle.

Django provides a unified calling API for these databases. We can choose different databases according to our business needs.

Mysql is the most commonly used database in Web applications. In this chapter, we will introduce Mysql as an example. You can use the MySQL tutorial Learn more about the basics of Mysql.

If you do not install mysql driver, you can execute the following command to install:

sudo pip install mysqlclient  #slower
pip install -i https://Pypi. Double. COM / simple / mysqlclient

1. Pycharmcreate Django

2. Database configuration

We found the DATABASES configuration item in the settings.py file of the project, and changed its information to:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # Or use mysql.connector.django
        'NAME': 'test',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST':'localhost',
        'PORT':'3306',
    }
}

Chinese comments are added here, so you need to add "× - * - coding: UTF-8 - * -" in the header of HelloWorld/settings.py file.

It contains the database name and user information, which are the same as the corresponding database and user settings in MySQL. According to this setting, Django connects with the corresponding databases and users in MySQL.

3. Define model

Create APP

Django states that if you want to use the model, you have to create an app. We use the following command to create an app for TestModel:

django-admin startapp TestModel

The directory structure is as follows:

HelloWorld
|-- TestModel
|   |-- __init__.py
|   |-- admin.py
|   |-- models.py
|   |-- tests.py
|   `-- views.py

We modify the TestModel/models.py file. The code is as follows:

# models.py
from django.db import models

class Test(models.Model):
    name = models.CharField(max_length=20)

The above class name represents the database table name and inherits the models.Model. The fields in the class represent the fields (names) in the data table. The data type is limited by the CharField (equivalent to varchar), DateField (equivalent to datetime) and max'length parameters.

Next, find the item "installed" apps in settings.py, as follows:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'TestModel',               # Add this item
)

Run on the command line:

$ python manage.py migrate   # Create table structure
//Failed available python3 manage.py migrate

$ python manage.py makemigrations TestModel  # Let Django know that we have some changes in our model
$ python manage.py migrate TestModel   # Create table structure

See a few lines of "Creating table "And your data table will be created.

After creation, you can view the following in Navicat for MySQL:

Creating tables ...
......
Creating table TestModel_test  #Our custom table
......

The structure of table name is: application name ﹣ class name (for example: testmodel ﹣ test).

Note: Although we do not set the primary key for the table in models, Django will automatically add an id as the primary key.

4. Database operations

Next, we add testdb.py file in HelloWorld directory (described below), and modify urls.py:

from django.contrib import admin
from django.urls import path
from . import testdb

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
]

Add data

To add data, you need to create an object first, and then execute the save function, which is equivalent to INSERT in SQL:

#HelloWorld/HelloWorld/testdb.py file code
# -*- coding: utf-8 -*-

from django.http import HttpResponse

from TestModel.models import Test

# Database operations
def testdb(request):
    test1 = Test(name='runoob')
    test1.save()
    return HttpResponse("<p>Data added successfully!</p>")

Visit http://127.0.0.1:8000/testdb You can see the prompt that the data is added successfully.

The output results are as follows:

The database can see:

Every time the browser refreshes, the information in the database will be added.

2, Recreate a Django

To delete the tables created in the database in advance

Run the project after creation

Will automatically jump to the browser

1. If you are continuing as above, you need the following steps:

(revert to original state)

  • Delete table file of test
  • Delete the XGPtest/XGPtest/testdb.py file created before
  • Content deletion of XGPtest/TestModel/models.py file
  • Comment on testdb in XGPtest/XGPtest/urls.py
  • Then restart

Browser access to http://127.0.0.1:8000/ will be the same as the previous interface, there is a small rocket!

  • Delete xgptest / testmodel / migrations / 0001 "initial.py file

2. Rebuild form

$ python manage.py migrate   # Create table structure
//Failed available python3 manage.py migrate

$ python manage.py makemigrations TestModel  # Let Django know that we have some changes in our model
$ python manage.py migrate TestModel   # Create table structure

3. Model.py file add type

#XGPtest/TestModel/models.py
from django.db import models

class Test(models.Model):
    name = models.CharField(max_length=20)

After the creation, the testmodel "U test table is generated in the database

4. About testdb in XGPtest/XGPtest/urls.py, uncomment

from django.contrib import admin
from django.urls import path
from . import testdb

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
]

3. Create the XGPtest/XGPtest/testdb.py test file

# -*- coding: utf-8 -*-

from django.http import HttpResponse

from TestModel.models import Test

# Database operations
def testdb(request):
    test1 = Test(name='runoob')
    test1.save()
    return HttpResponse("<p>Data added successfully!</p>")

4. Get data

First visit http://127.0.0.1:8000/testdb several times to generate data

Change the contents of the database (write at will)

Django provides many ways to get the contents of the database, as shown in the following code:

#XGPtest/XGPtest/testdb.py#Add at the end of XGPtest/XGPtest/testdb.py file
def getdb(request):
    # Initialization
    response = ""
    response1 = ""

    # Get all data rows through all() of objects, the model manager, which is equivalent to SELECT * FROM in SQL
    list = Test.objects.all()

    # Filter is equivalent to WHERE in SQL. You can set conditions to filter results
    response2 = Test.objects.filter(id=1)

    # Get single object
    response3 = Test.objects.get(id=1)

    # Limit the returned data is equivalent to OFFSET 0 LIMIT 2 in SQL;
    # Test.objects.order_by('name')[0:2]

    # Data sorting
    Test.objects.order_by("id")

    # The above method can be used in chain
    Test.objects.filter(name="runoob").order_by("id")

    # Output all data
    for var in list:
        response1 += var.name + " "
    response = response1
    return HttpResponse("<p>" + response + "</p>")

XGPtest/XGPtest/urls.py file add

from django.contrib import admin
from django.urls import path
from . import testdb

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.gitdb),         #Add to
]
Browser: https://www.runoob.com/django/django-model.html

5. Update data

To modify data, you can use save() or update():

#XGPtest/XGPtest/testdb.py#Add at the end of XGPtest/XGPtest/testdb.py file
def modify(request):
    # Modify the name field with id=1 and save, which is equivalent to the UPDATE in SQL
    test1 = Test.objects.get(id=1)
    test1.name = 'Google'
    test1.save()

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

    # Modify all columns
    # Test.objects.all().update(name='Google')

    return HttpResponse("<p>Modified success</p>")

XGPtest/XGPtest/urls.py file add

from django.contrib import admin
from django.urls import path
from . import testdb

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.gitdb),         #Add to
    path('modify/', testdb.modify), 
]
Browser visit http://127.0.0.1:8000/modify/

View the testmodel? Test table of the test database

6. Delete data

To delete an object in the database, simply call the delete() method of the object:

#XGPtest/XGPtest/testdb.py#Add at the end of XGPtest/XGPtest/testdb.py file
def del(request):
    # Delete data with id=1
    test1 = Test.objects.get(id=1)
    test1.delete()

    # Another way
    # Test.objects.filter(id=1).delete()

    # Delete all data
    # Test.objects.all().delete()

    return HttpResponse("<p>Delete successful</p>")

XGPtest/XGPtest/urls.py file add

from django.contrib import admin
from django.urls import path
from . import testdb

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.gitdb),         #Add to
    path('modify/', testdb.modify), 
    path('del/', testdb.del),
]
Browser access http://127.0.0.1:8000/del

Database to see if the first data is deleted

3, Django form

HTML forms are a classic way for web site interaction. This chapter describes how to use Django to process form data submitted by users.

1. HTTP request

The HTTP protocol works in a "request reply" fashion. When a customer sends a request, data can be attached to the request. By parsing the request, the server can obtain the data from the client and provide specific services according to the URL.

2. GET method

We created a search.py file in the previous project to receive the user's request:

#/HelloWorld/HelloWorld/search.py file code:
# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render

# form
def search_form(request):
    return render(request,'search_form.html',{})

# Receive request data
def search(request):
    request.encoding = 'utf-8'
    if 'q' in request.GET and request.GET['q']:
        message = 'What you search for is: ' + request.GET['q']
    else:
        message = 'You submitted an empty form'
    return HttpResponse(message)

Add the search form.html form to the template directory templates:

#/HelloWorld / templates / search form.html file code:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>xgp666</title>
</head>
<body>
<form action="/search" method="get">
    <input type="text" name="q">
    <input type="submit" value="search">
    </form>
</body>
</html>

Can be opened in the browser is a search box

The urls.py rule is modified as follows:

#/HelloWorld/HelloWorld/urls.py file code:
from django.contrib import admin
from django.urls import path
from . import testdb
from . import search

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.getdb),
    path('modify/', testdb.modify),
    path('del/', testdb.dl),
    path('search/', search.search),
    path('search-from/', search.search_form),
]

Access address http://127.0.0.1:8000/search-form And search as follows:

Analysis

3. POST method

We used the GET method above. View display and request processing are divided into two functions.

POST method is more commonly used when submitting data. Let's use this method and use a URL and handler to display the view and process the request at the same time.

We create post.html in templates:

#/HelloWorld/templates/post.html file code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>xgp666</title>
</head>
<body>
    <form action="/search-post/" method="post">
        {% csrf_token %}
        <input type="text" name="q">
        <input type="submit" value="Submit">
    </form>

    <p>{{ rlt }}</p>
</body>
</html>

At the end of the template, we add an rlt token to reserve a place for the table processing results.

There is also a label for {% csrf [u token%} after the table. The full name of csrf is cross site request forge. This is Django's ability to prevent requests from being submitted in disguise. The form submitted by the POST method must have this label.

Create a new search2.py file in the HelloWorld directory and use the search ﹣ POST function to process the POST request:

#/HelloWorld/HelloWorld/search2.py file code:
# -*- coding: utf-8 -*-

from django.shortcuts import render
from django.views.decorators import csrf

# Receive POST request data
def search_post(request):
    ctx ={}
    if request.POST:
        ctx['rlt'] = request.POST['q']
    return render(request, "post.html", ctx)

The urls.py rule is modified as follows:

#/HelloWorld/HelloWorld/urls.py file code:
from django.contrib import admin
from django.urls import path
from . import testdb
from . import search
from . import search2

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.getdb),
    path('modify/', testdb.modify),
    path('del/', testdb.dl),
    path('search/', search.search),
    path('search-from/', search.search_form),
    path('search-post/', search2.search_post),
]

Visit http://127.0.0.1:8000/search-post The results are as follows:

4, Django Admin administration tool

Django provides a web-based management tool.

The Django automated management tool is part of django.contrib. You can see it in installed Apus in settings.py of the project:

#/HelloWorld/HelloWorld/settings.py file code:
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

django.contrib is a huge set of functions, which is a part of Django basic code.

1. Activate management tools

Usually we will set it in urls.py automatically when we build the project. We just need to remove the comments.

The configuration items are as follows:

#/HelloWorld/HelloWorld/urls.py file code:
from django.contrib import admin
from django.urls import path
from . import testdb
from . import search
from . import search2

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.getdb),
    path('modify/', testdb.modify),
    path('del/', testdb.dl),
    path('search/', search.search),
    path('search-from/', search.search_form),
    path('search-post/', search2.search_post),
]

When all this is configured, the Django administration tool is ready to run.

2. Using management tools

Start the development server and access it in the browser http://127.0.0.1:8000/admin/, get the following interface:

Because I have created a new project, I need to create a table structure:

$ python manage.py migrate   # Create table structure
//Failed available python3 manage.py migrate

$ python manage.py makemigrations TestModel  # Let Django know that we have some changes in our model
$ python manage.py migrate TestModel   # Create table structure

You can create a superuser by issuing the command python manage.py createsuperuser, as follows:

# python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: admin@runoob.com
Password:
Password (again):
Superuser created successfully.

Then enter the user name and password to log in. The interface is as follows:

Model.py file add type

#XGPtest/TestModel/models.py
from django.db import models

class Test(models.Model):
    name = models.CharField(max_length=20)

After the creation, the testmodel "U test table is generated in the database

In order for the admin interface to manage a data model, we need to register the data model to admin first. For example, we have created the model Test in the TestModel before. Modify TestModel/admin.py:

#HelloWorld/TestModel/admin.py: file code:
from django.contrib import admin
from. models import Test

# Register your models here.
admin.site.register(Test)
After refreshing, you can see the Testmodel data table:

It can be simply added, modified and deleted.

3. Add a user using administrative tools

4. Complex model

The function of management page is powerful, and it has the ability to deal with more complex data model.

First, add a more complex data model to TestModel/models.py:

from django.db import models

# Create your models here.
class Test(models.Model):
    name = models.CharField(max_length=20)

class Contact(models.Model):
    name   = models.CharField(max_length=20)
    age    = models.IntegerField(default=0)
    email  = models.EmailField()
    def __unicode__(self):
        return self.name

class Tag(models.Model):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE,)
    name    = models.CharField(max_length=50)
    def __unicode__(self):
        return self.name

Here are two watches. Tag takes Contact as the external key. A Contact can correspond to multiple tags.

We can also see many attribute types that we haven't seen before, such as IntegerField, used to store integers.

Register multiple models in TestModel/admin.py and display:
from django.contrib import admin
from TestModel.models import Test,Contact,Tag

# Register your models here.
admin.site.register([Test, Contact, Tag])

Refresh the management page, and the results are as follows:

In the above management tools, we can operate complex models.

If you have not created a table structure before, use the following command to create it:

$Python management.py makemigrations testmodel let Django know that we have some changes in our model
 $python manage.py migrate TestModel create table structure

**The database will generate new forms testmodel tag and testmodel Contacts)

5. Custom form

We can customize the management page to replace the default page. For example, the "add" page above. We want to show only the name and email parts. Modify TestModel/admin.py:

#HelloWorld/TestModel/admin.py: file code:
from django.contrib import admin
from . models import Test,Contact,Tag

class ContactAdmin(admin.ModelAdmin):
    fields = ('name', 'email')

# Register your models here.
admin.site.register(Contact, ContactAdmin)
admin.site.register([Test, Tag])

The above code defines a ContactAdmin class to describe the display format of the management page.

The fields attribute inside defines the fields to display.

Because this class corresponds to the Contact data model, we need to register them together when registering. The display effect is as follows:

We can also block the input fields, and each column can also define its own format. Modify TestModel/admin.py to:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class ContactAdmin(admin.ModelAdmin):
    fieldsets = (
        ['Main', {
            'fields': ('name', 'email'),
        }],
        ['Advance', {
            'classes': ('collapse',),  # CSS
            'fields': ('age',),
        }]
    )

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test, Tag])

The above column is divided into two parts: Main and Advance. classes describes the CSS format of the part it is in. Let the Advance section hide:

There is a Show button next to the Advance part for expansion. After expansion, you can click Hide to hide it, as shown in the following figure:

6. Inline display

The above Contact is the external key of Tag, so it has an external reference relationship.

In the default page display, separating the two can't show their affiliation. We can use inline display to have Tag attached to the edit page of the Contact.

Modify TestModel/admin.py:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class TagInline(admin.TabularInline):
    model = Tag

class ContactAdmin(admin.ModelAdmin):
    inlines = [TagInline]  # Inline
    fieldsets = (
        ['Main', {
            'fields': ('name', 'email'),
        }],
        ['Advance', {
            'classes': ('collapse',),
            'fields': ('age',),
        }]

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test, Tag])
The display effect is as follows:

7. Display of list page

After the Contact enters several records, the list page of the Contact looks like this:

We can also customize the display of this page. For example, to display more columns in the list, just add the list "display attribute in ContactAdmin:

#HelloWorld/TestModel/admin.py: file code:
from django.contrib import admin
from TestModel.models import Test,Contact,Tag

# Register your models here.
class TagInline(admin.TabularInline):
    model = Tag

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name','age', 'email') # list
    inlines = [TagInline]  # Inline
    fieldsets = (
        ['Main',{
            'fields':('name','email'),
        }],
        ['Advance',{
            'classes': ('collapse',),
            'fields': ('age',),
        }]

    )

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test])
The refresh page displays as follows:

The search function is very useful in managing a large number of records. We can use search fields to add a search column to the list page:

#HelloWorld/TestModel/admin.py: file code:
from django.contrib import admin
from TestModel.models import Test,Contact,Tag

# Register your models here.
class TagInline(admin.TabularInline):
    model = Tag

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name','age', 'email')
    search_fields = ('name',)               #search
    inlines = [TagInline]  # Inline
    fieldsets = (
        ['Main',{
            'fields':('name','email'),
        }],
        ['Advance',{
            'classes': ('collapse',),
            'fields': ('age',),
        }]

    )

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test])
In this example, we search the record with name xgp, and the result is as follows:

5, Import static file

File link link: https://pan.baidu.com/s/133f0ypYOsAi8s8DdV_Uduw Extraction code: 4847

You need to introduce some static resources into the project, create a new static directory, and put js, css and other files in this directory:

1. The urls.py rule is modified as follows:

from django.contrib import admin
from django.urls import path
from . import testdb
from . import search
from . import search2
from . import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('testdb/', testdb.testdb),
    path('gitdb/', testdb.getdb),
    path('modify/', testdb.modify),
    path('del/', testdb.dl),
    path('search/', search.search),
    path('search-from/', search.search_form),
    path('search-post/', search2.search_post),
    path('index/', index.index),
]

2. Create index.py file in this directory

from django.shortcuts import render

def index(request):
    return render(request, 'index.html' ,{})

Browser Check it out.

3. Django needs to find this directory and configure it in the setting file:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

4. Modify the index.html file

To introduce static resources into html files:

Replace all images in the index.html file with {{static} / image!

ctrl+F: replace

Browser Check it out.

Tags: Python Django Database MySQL

Posted on Sat, 18 Apr 2020 10:05:03 -0700 by sanam