Experience and skills summary of Python Django development

Keywords: Django Database SQL Attribute

Article directory

1. Data transfer between front and back stations

View - > HTML: using Django template
views.py Code:

from django.shortcuts import render
def main_page(request):
    data = [1,2,3,4]
    return render(request, 'index.html', {'data': data})

Get data with {}} in HTML

<div>{{ data }}</div>

The data that can be iterated can be iterated:

{% for item in data%}
<p>{{ item }}</p>
{% endfor %}

This method can pass various data types, including list, dict and so on.

2. Several common methods of interacting with database and returning data

models.UserInfo.objects.all()
models.UserInfo.objects.all().values('user')    #user column only
models.UserInfo.objects.all().values_list('id','user')    #Take the id and user columns and generate a list
models.UserInfo.objects.get(id=1)
models.UserInfo.objects.get(user='cucucu')

3. Solutions of multiple buttons corresponding to one form

Add different name attributes for different buttons, and then judge the name value in the background

<form method="post" action="Self determination" οnsubmit="return">
<button type="submit" class="btn btn-info" name="del">delete</button>
<button type="submit" class="btn btn-info" name="update">To update</button>
</form>

And then realize different functions through different name s

def function(request):
    if request.POST:
        if if 'update' in request.POST:
            ...      #update function implementation
        else:
            ...      #del function realization
        return render(request, 'xxx.html', yyy)

4. Form control and operation in HTML

In HTML, the form is usually written as follows:

<form method="post" action=""> 
<! - this method represents a method. Generally, there are two methods: one is' post ', the other is' get'. The action is where to submit the form. You can fill in a URL. If it is not filled in, it defau lt s to this page. >

{%csrf_token%} 
<! - this is a tag in django, which is used to prevent malicious attacks. If you don't add this tag, you will encounter the problem that you can't submit. It's a little troublesome to deal with. It's recommended to add it. >

<input name="select" type="radio" value='radio'>
<! - this is a radio label. Mu lt iple choices are type='checkbox '. Value is the displayed content, and it is also used as a value after the backend submits. name is used by the backend to get the value of this radio button. For example, the backend uses select = request.POST['select '] to get the value of this radio button, or select = request.POST.get('select',None). >

< input name = "submit" type = "submit" value = "submit" / >
<! - this is a reference control, in which type='submit 'ensures that the content in the form (< form > < / form >) will be submitted to the backend after clicking. >

<input name="text" type="text" value="" />
<! - one input box >

</form>

<! - end of form >

Front end HTML code:

<!DOCTYPE html>

<html lang="en">

<head>

 <meta charset="UTF-8">

 <title>Title</title>

</head>

<body>

<form method="post" action=""> 

{%csrf_token%}

<input name="select" type="radio" value='radio'>

<input name="text" type="text" value="" />

<input name="submit" type="submit" value="Submission" />

</form>

</body>

</html>

The back end writes a function in views.py to accept the data passed in from the front end:

def receive_data(request):
if request.POST: # If data submitted
	print('Submit')
	select = request.POST.get('select',None)
	text = request.POST.get('text',None)
	print(select,text)
return render(request,'your_html.html', locals()) # Change your html.html to your HTML page and create a url link by referring to the previous blog.

5. Message frame message usage

Message level:

level Explain
DEBUG Development related messages that will be ignored (or deleted) in the production deployment
INFO General tips
SUCCESS Success information
WARNING Warning message
ERROR Error messages that have occurred

This function uses the django.contrib.messages library to register part of the APP in the setting.py file of Django project

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',  # Custom APP registration
]

In backend views.py

from django.contrib import messages

def abc(request):
    messages.debug(request, '%s SQL statements were executed.' % count)
	messages.info(request, 'Three credits remain in your account.')
	messages.success(request, 'Profile details updated.')
	messages.warning(request, 'Your account expires in three days.')
	messages.error(request, 'Document deleted.')

perhaps

from django.contrib import messages

def abc(request):
    messages.add_message(request, messages.INFO, 'Hello world.')

Front end display

{% if messages %}
    <script>
        {% for msg in messages %}
            alert('{{ msg.message }}');
        {% endfor %}
    </script>
{% endif %}

6. Auto now, auto now add of DateField

When creating django's model, there are three types of date time field, DateField and TimeField that can be used to create date fields. Their values correspond to the objects in date time(), date(), and time(), respectively. These three fields have the same parameters auto ﹣ now ﹣ and auto ﹣ now ﹣ add.
auto_now:
The default value of this parameter is false. When it is set to true, the value of this field can be set to the current time when the field is saved, and it will be updated automatically every time the model is modified. Therefore, this parameter is very convenient in the scenario where the "last modification time" needs to be stored. It should be noted that setting this parameter to true does not simply mean that the default value of the field is the current time, but that the field will be "forced" to update to the current time. You cannot manually assign a value to the field in the program. If you use the admin manager of django, the field is read-only in admin.
auto_now_add:
When set to True, the value of the field will be set to the time of creation when the model object is first created. When the object is modified later, the value of the field will not be updated. This attribute is usually used in scenarios where the creation time is stored. Similar to auto now, auto now add is also mandatory. Once it is set to True, fields cannot be assigned manually in the program and become read-only in admin.

7. Get the name of the logged in user

The value in views is request.user.username, and the value in template page is {request. User}}. It is {% if request. User. Is [authenticated%}

8. Auto increment / Auto decrement of attributes in database tables

It can be implemented more quickly and robustly through relatively updated operations, rather than explicitly assigning new values. Django provides F() expression for relative update operation

from django.db.models import F
product = Product.objects.get(name='Venezuelan Beaver Cheese')
product.number_sold = F('number_sold') + 1
product.save()

This method does not use the specific original value in the database. Instead, when save() is executed, the database will update according to the current value of the database;
Once the current object is stored, we must reload the current object to get the latest value in the current database.

9. Execute the original sql statement

(1) extra() method:
Result set modifier, a mechanism that provides additional query parameters.

Book.objects.filter(publisher__name='Guangdong People's Publishing House').extra(where=['price>50'])
Book.objects.filter(publisher__name='Guangdong People's Publishing House',price__gt=50)
Book.objects.extra(select={'count':'select count(*) from hello_Book'})

(2) raw() method:
The raw() method of the manager can be used to execute the original SQL and return the model instance:
Manager.raw(raw_query, params=None, translations=None)
Using raw:

Book.objects.raw('select * from hello_Book')

Custom sql:

Book.objects.raw("insert into hello_author(name) values('test')")

rawQuerySet is an inert query, which will be executed only when it is used.
May refer to https://www.cnblogs.com/fmgao-technology/p/10119671.html#_labelTop

10. Pagination display data

python backend:
urls.py:

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index1$', views.index1),
]

views.py:

from django.shortcuts import render
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
# Create your views here.

#Simply create a lot of data to test
USER_LIST=[]
for i in range(1,999):
    temp={'name':'root'+str(i),'age':i}
    USER_LIST.append(temp)


def index1(request):
    # All data: user ﹣ list, =, how many pieces of data are there
    # Per page: number of entries per page
    # count: total number of data
    # Num pages: total pages
    # page_range: index range of total pages, such as: (1,10), (1200)
    # Page: page object (whether it has the next page; whether it has the previous page;)
    current_page = request.GET.get('p')  #Current page number
    current_page=int(current_page)
    # Paginator object
    paginator = Paginator(USER_LIST,10)   # 10 data on one page
    
	#Add judgment: when the total number of pages is more than 10, part of them will not be displayed
    if paginator.num_pages > 10:
        if current_page - 5 < 1:
            posts_list = range(1, 11)
        elif current_page+ 5 > paginator.num_pages:
            posts_list = range(current_page - 5, paginator.num_pages + 1)
        else:
            posts_list = range(current_page - 5, current_page + 5)
    else:
    	#Show all when less than or equal to 10 pages
        posts_list = paginator.page_range
        
    try:
        # Page object
        posts = paginator.page(current_page)
        # Has next page
        # Next page number
        # Has previous
        # Previous page number
        # Object list: the list of data after pagination. The sliced data
        # number current page
        # Paginator Paginator object
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render(request, 'index1.html', {'posts': posts,"posts_list":posts_list})

Front end display:
index1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<ul>
    {% for row in posts.object_list %}
    <li>{{row.name}}----------------{{row.age}}</li>
    {% endfor %}
</ul>
{% if posts.has_previous %}
    <a href="/index1?p={{posts.previous_page_number}}">Previous page</a>
{% else %}
    <a href="#">Previous page</a>
{%endif%}

{% for index in posts_list%}
    {% if index == posts.number %}
        <a href="#" style="color: black">{{index}}</a>
    {% else %}
        <a href="/index1?p={{index}}">{{index}}</a>
    {% endif %}
{% endfor %}

{% if posts.has_next %}
    <a href="/index1?p={{posts.next_page_number}}">next page</a>
{% else %}
    <a href="#">next page</a>
{%endif%}
<span>
    {{posts.number}}/{{posts.paginator.num_pages}}
</span>


</body>
</html>

52 original articles published, 184 praised, 30000 visitors+
Private letter follow

Posted by Ilovetopk on Sat, 18 Jan 2020 04:11:04 -0800