PyCharm implementation (Django models, forms, management tools, introduction of static files)

1. Django model (PyCharm implementation)

Django provides good support for various databases, including: PostgreSQL, MySQL, SQLite, 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 use Mysql as an example. You can learn more about the basics of Mysql through the MySQL tutorial on this site .

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

sudo pip install mysqlclient  #较慢
pip install -i https://pypi.douban.com/simple/  mysqlclient  #较快

1. PyCharm creates Django

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

2. Database configuration

We find the DATABASES configuration item in the settings.py file of the project and modify its information to:

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

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Chinese comments are added here, so you need to add #-*-coding: UTF-8-*-at the head of the HelloWorld / settings.py file.

The above 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 to the corresponding database and user in MySQL.

3. Define the model

Create APP

Django stipulates that if you want to use the model, you must create an app. We use the following command to create a TestModel app:

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 name of the database table, and inherited models.Model. The fields in the class represent the fields in the data table (name), and the data type is defined by CharField (equivalent varchar), DateField(equivalent datetime), and the max_length parameter defines the length.

Next, find the INSTALLED_APPS item 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',               # 添加此项
)

Run from the command line:

$ python manage.py migrate   # 创建表结构
//失败了可用python3 manage.py migrate

$ python manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更
$ python manage.py migrate TestModel   # 创建表结构

Seeing a few lines of "Creating table ...", your data table is created.

After creating it, you can view it in Navicat for MySQL:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Creating tables ...
……
Creating table TestModel_test  #我们自定义的表
……

The table name structure is: application name_class name (eg: TestModel_test).

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

4. Database operation

Next we add the testdb.py file (described below) to the HelloWorld directory 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),
]

adding 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文件代码
# -*- coding: utf-8 -*-

from django.http import HttpResponse

from TestModel.models import Test

# 数据库操作
def testdb(request):
    test1 = Test(name='runoob')
    test1.save()
    return HttpResponse("<p>数据添加成功!</p>")

Visit http://127.0.0.1:8000/testdb to see the prompt of successful data addition.

The output is as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

The database can see:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Each time the browser refreshes, the information in the database will increase.

Second, re-create a Django

To delete the table created in the database in advance

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Run this project after creation

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Will automatically jump to the browser

PyCharm implementation (Django models, forms, management tools, introduction of static files)

1. If you continue to do as above, the following steps are required:

(Revert to the original state)

  • Delete the test table file
  • Delete the XGPtest / XGPtest / testdb.py file created earlier
  • XGPtest / TestModel / models.py file content deleted
  • Note the content about 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 the XGPtest / TestModel / migrations / 0001_initial.py file

2. Regenerate the form

$ python manage.py migrate   # 创建表结构
//失败了可用python3 manage.py migrate

$ python manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更
$ python manage.py migrate TestModel   # 创建表结构

3. Types added to the models.py file

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

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

After the creation is complete, the testmodel_test table is generated in the database

4. Uncomment the content about testdb in XGPtest / XGPtest / 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),
]

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

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

from django.http import HttpResponse

from TestModel.models import Test

# 数据库操作
def testdb(request):
    test1 = Test(name='runoob')
    test1.save()
    return HttpResponse("<p>数据添加成功!</p>")

4. Get data

First visit a few times to generate data at http://127.0.0.1:8000/testdb

Change the contents of the database (write at random)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Django provides multiple ways to obtain the contents of the database, as shown in the following code:

#XGPtest/XGPtest/testdb.py#XGPtest/XGPtest/testdb.py 文件尾部添加
def getdb(request):
    # 初始化
    response = ""
    response1 = ""

    # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM
    list = Test.objects.all()

    # filter相当于SQL中的WHERE,可设置条件过滤结果
    response2 = Test.objects.filter(id=1)

    # 获取单个对象
    response3 = Test.objects.get(id=1)

    # 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
    # Test.objects.order_by('name')[0:2]

    # 数据排序
    Test.objects.order_by("id")

    # 上面的方法可以连锁使用
    Test.objects.filter(name="runoob").order_by("id")

    # 输出所有数据
    for var in list:
        response1 += var.name + " "
    response = response1
    return HttpResponse("<p>" + response + "</p>")

XGPtest / XGPtest / urls.py file added

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),         #添加
]
Browser visit https://www.runoob.com/django/django-model.html

PyCharm implementation (Django models, forms, management tools, introduction of static files)

5. Update data

Modify data can use save () or update ():

#XGPtest/XGPtest/testdb.py#XGPtest/XGPtest/testdb.py 文件尾部添加
def modify(request):
    # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
    test1 = Test.objects.get(id=1)
    test1.name = 'Google'
    test1.save()

    # 另外一种方式
    #Test.objects.filter(id=1).update(name='Google')

    # 修改所有的列
    # Test.objects.all().update(name='Google')

    return HttpResponse("<p>修改成功</p>")

XGPtest / XGPtest / urls.py file added

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),         #添加
    path('modify/', testdb.modify), 
]
Browser visit http://127.0.0.1:8000/modify/

PyCharm implementation (Django models, forms, management tools, introduction of static files)

View test database testmodel_test table

PyCharm implementation (Django models, forms, management tools, introduction of static files)

6. Delete data

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

#XGPtest/XGPtest/testdb.py#XGPtest/XGPtest/testdb.py 文件尾部添加
def del(request):
    # 删除id=1的数据
    test1 = Test.objects.get(id=1)
    test1.delete()

    # 另外一种方式
    # Test.objects.filter(id=1).delete()

    # 删除所有数据
    # Test.objects.all().delete()

    return HttpResponse("<p>删除成功</p>")

XGPtest / XGPtest / urls.py file added

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),         #添加
    path('modify/', testdb.modify), 
    path('del/', testdb.del),
]
Browser visit http://127.0.0.1:8000/del

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Check whether the first data is deleted in the database

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Three, Django forms

HTML forms are a classic way of website interactivity. This chapter will introduce how to use Django to process the form data submitted by users.

1. HTTP request

The HTTP protocol works in a "request-reply" way. When a customer sends a request, they can attach data to the request. By parsing the request, the server can obtain the data from the client and provide specific services based on the URL.

2. The GET method

We created a search.py ​​file in the previous project to receive user requests:

#/HelloWorld/HelloWorld/search.py 文件代码:
# -*- coding: utf-8 -*-

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

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

# 接收请求数据
def search(request):
    request.encoding = 'utf-8'
    if 'q' in request.GET and request.GET['q']:
        message = '你搜索的内容为: ' + request.GET['q']
    else:
        message = '你提交了空表单'
    return HttpResponse(message)

Add the search_form.html form in the templates directory templates:

#/HelloWorld/templates/search_form.html 文件代码:
<!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="搜索">
    </form>
</body>
</html>

Can be opened in the browser is a search box

PyCharm implementation (Django models, forms, management tools, introduction of static files)

The urls.py rule is modified to the following form:

#/HelloWorld/HelloWorld/urls.py 文件代码:
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),
]

Visit the address http://127.0.0.1:8000/search-form and search, the result is as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Analyze

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

3. POST method

Above we used the GET method. View display and request processing are divided into two functions.

The POST method is more commonly used when submitting data. We use this method below, and use a URL and processing function to simultaneously display the view and process the request.

We create post.html in templates:

#/HelloWorld/templates/post.html 文件代码:
<!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 mark to reserve a place for the table processing results.

There is also a {% csrf_token%} label behind the table. The full name of csrf is Cross Site Request Forgery. This is a feature provided by Django to prevent submission requests from being disguised. Forms 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 POST requests:

#/HelloWorld/HelloWorld/search2.py 文件代码:
# -*- coding: utf-8 -*-

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

# 接收POST请求数据
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 to the following form:

#/HelloWorld/HelloWorld/urls.py 文件代码:
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 and the results are as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Four, Django Admin management tool

Django provides web-based management tools.

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

#/HelloWorld/HelloWorld/settings.py 文件代码:
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 features, it is an integral part of Django's basic code.

1. Activate management tools

Usually we will automatically set it in urls.py when generating the project, we just need to remove the comment.

The configuration items are as follows:

#/HelloWorld/HelloWorld/urls.py 文件代码:
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 of this is configured, the Django management tools can be run.

2. Use management tools

Start the development server, and then visit http://127.0.0.1:8000/admin/ in the browser to get the following interface :

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Because I am creating a new project now, I need to create a table structure:

$ python manage.py migrate   # 创建表结构
//失败了可用python3 manage.py migrate

$ python manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更
$ python manage.py migrate TestModel   # 创建表结构

You can create a super user by the command python manage.py createsuperuser , as shown below:

# python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.

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

PyCharm implementation (Django models, forms, management tools, introduction of static files)

models.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 is complete, the testmodel_test table is generated in the database

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

#HelloWorld/TestModel/admin.py: 文件代码:
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:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Can be simply added, modified and deleted.

3. Use the management tool to add a user

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

4. Complex model

The management page is powerful and fully capable of handling more complex data models.

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

There are two tables. Tag uses Contact as the external key. A Contact can correspond to multiple tags.

We can also see many attribute types that have not been seen before, such as IntegerField for storing integers.

PyCharm implementation (Django models, forms, management tools, introduction of static files)

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, the display results are as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

With the above management tools, we can perform complex model operations.

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

$ python manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更
$ python manage.py migrate TestModel   # 创建表结构

** The database will generate new forms testmodel tagandtestmodel Contacts )

5. Custom form

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

#HelloWorld/TestModel/admin.py: 文件代码:
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 explain the display format of the management page.

The fields attribute inside defines the fields to be displayed.

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

PyCharm implementation (Django models, forms, management tools, introduction of static files)

PyCharm implementation (Django models, forms, management tools, introduction of static files)

We can also divide the input fields into blocks, and each field 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 column above is divided into two parts, Main and Advance. classes specifies the CSS format of the part it is in. Here, the Advance part is hidden:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

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

PyCharm implementation (Django models, forms, management tools, introduction of static files)

6. Inline display

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

In the default page display, separating the two cannot reflect the subordinate relationship between the two. We can use inline display to have the Tag attached to the contact's edit page.

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:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

7. Display of the list page

After entering several records in Contact, the list page of Contact looks as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

We can also customize the display of the page. For example, to display more columns in the list, we only need to add the list_display attribute in ContactAdmin:

#HelloWorld/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):
    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 effect of refreshing the page is as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

The search function is very useful when managing a large number of records. We can use search_fields to add a search bar to the list page:

#HelloWorld/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):
    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 searched for the record whose name is xgp, and the display result is as follows:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Five, the introduction of static files

File link `` Link: https://pan.baidu.com/s/133f0ypYOsAi8s8DdV_Uduw extraction code: 4847 ''

Need to introduce some static resources into the project, create a new static directory, you can put js, css and other files into this directory:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

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

PyCharm implementation (Django models, forms, management tools, introduction of static files)

3. You need to let Django find this directory, which needs to be configured in the setting file:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

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

4. Modify the index.html file

Introduce static resources in the html file:

PyCharm implementation (Django models, forms, management tools, introduction of static files)

imageReplace all in the index.html file with {{ STATIC_URL }}/image!

ctrl + F: Replace

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Browser check

PyCharm implementation (Django models, forms, management tools, introduction of static files)

Guess you like

Origin blog.51cto.com/14320361/2488446