Django basics -- View

        This is Qing'an. Notes are indispensable. Let's take a look at the notes and views of this article. V: qing_an_an

        All the above are get requests. Let's talk about post in this chapter. By the way, let's study together. The template returns data.

        Please prepare the database!!!

                django-admin startproject testproject        

                manage.py startapp testapp         

                manage.py migrate

        After creation, we directly enter the model interface and add some fields required by the database:

class User(models.Model):
 username = models.CharField(max_length=20)
 password = models.CharField(max_length=20)
 create_time = models.DateTimeField(auto_now_add=True)
 update_time = models.DateTimeField(auto_now=True)

        Remember to submit synchronously!!! Otherwise, an error will be reported later. Create here_ Time is the time of creation, update_time is the time of the change.

Add data

        Next, edit the view:

from .models import User

def create_user(request):
    print(request.POST['username'])
    print(request.POST['password'])

    username = request.POST['username']
    password = request.POST['password']
    data = {'username':username,'password':password}
    obj = User.objects.all()
    obj.create(**data)
    return render(request,'create_user.html')

def get_create_user_html(request):

    return render(request,'create_user.html')

        Add route:

from testqing.views import *

urlpatterns = [
    path('create/user/',create_user),
    path('create/',get_create_user_html),
]

        This view is mainly used to add data functions. As for the request method, we need to set it in the template. there

User.objects.all() is added for all fields in the model. get_create_user_html is that after we send the first data, we enter create through the template_ In user routing, continue data transmission.

        See how the template says:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QingAn</title>
</head>
<body>
{# method Change access method #}
<form action="/create/user/" method="post">
    {% csrf_token %}
    user name:<input type="text" name="username">
    password:<input type="text" name="password">
    <input type="submit" value="Submit">
</form>

</body>
</html>

        The route is specified here, that is, we first enter the create route, enter the user name and password, click the submit button, and the data will be sent through the / create/user / route and in the form of post request to the database. And it will be printed out in control Taishan. Note: the reason why it is allowed here is because the print in the previous code.

         {% csrf_token%} anti counterfeiting interception of cross site requests can be solved here. If this is removed, it will be intercepted.

         Verification is personal verification. Enter the database and refresh it.

Query data

def search_user(request):
    # Build an input, determine the return data type, and then decide how to write in the template
    username = request.GET['username']
    # Search function of building model
    user_obj = User.objects.filter(username=username)
    data = dict()
    for i in user_obj:
        # print(i.__dict__)
        data.update({i.__dict__['id']: i.__dict__})
    data = {'data':data}
    return render(request,'search_user.html',data)

        There are not many requirements for querying data. The default is get. The filter in User.objects.filter(username=username) mentioned earlier. The filter method accepts the content of complex state and empty object content, and returns a list of objects in complex state.

   This involves data conversion. Use the for loop to traverse the data, then pass it in the form of a dictionary, and then print it out again through the for loop in the template to get the expected result value.

   How to write the template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QingAn</title>
</head>
<body>
<form action="/search/user/" method="get">
   Please enter a search user: <input type="text" name="username">
    <input type="submit" value="search">
</form>

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Password</th>
    </tr>
    {% for d in data.values %}
        <tr>
            <td>{{ d.id }}</td>
            <td>{{ d.username }}</td>
            <td>{{ d.password }}</td>
        </tr>
    {% endfor %}

</table>
</body>
</html>

        There is a premise here, that is, you must have enough data in the database, and you must have the right data when searching.

         What should you do if you search for ID first? Change the name="username" in the view to name="id", and change the request.GET['username '] in the view to request.GET['id'], user_obj = User.objects.filter(username=username) can be changed to id=username.

        If the ID in data. Update ({I. _dict_ ['id ']: I. _dict_}) is changed to username, only the latest added data will be displayed during query.

Modify data

         View code:

def update_user(request):
    user = User.objects.get(id=request.POST["id"])
    username = request.POST["username"]
    password = request.POST["password"]
    user.__dict__.update({
        "username": username,
        "password": password
    })
    user.save()
    users_object = User.objects.all()
    data = dict()
    for i in users_object:
        data.update({i.pk: {
            "username": i.username,
            "password": i.password,
            "id": i.id,
        }})
    data = {"data": data}
    return render(request, "update_user.html", data)

def get_update_user(request):
    users_object = User.objects.all()
    data = dict()
    for i in users_object:
    # username = i.username
    # password = i.password
    # pk = i.pk
        data.update({i.pk: {
            "username": i.username,
            "password": i.password,
            "id": i.pk,
        }})
    data = {"data": data}
    return render(request,'update_user.html',data)

        Routing code:

from testqing.views import *

urlpatterns = [
    path('update/user/',update_user),
    path('update/',get_update_user),
]

        Template code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QingAn</title>
</head>
<body>

    <table>
        <tr>
            <th>ID</th>
            <th>username</th>
            <th>password</th>
            <th>Submit changes</th>
        </tr>
        {% for d in data.values %}
            <tr>
                <form action="/update/user/" method="post">
                    <td>
                        <input type="text" name="id" value="{{d.id }}">
                    </td>
                    <td>
                        <input type="text" name="username" value="{{ d.username }}">
                    </td>
                    <td>
                        <input type="text" name="password" value="{{d.password }}">
                    </td>
                    <td>
                        <input type="submit" value="Submit">
                    </td>
                </form>
            </tr>
        {% endfor %}
    </table>

</body>
</html>

        Let's see the effect:

         After modification, click Submit and enter the database to see that the data has been modified.

Delete data

        View code:

def get_delete_user(request):
    users_object = User.objects.all()
    data = dict()
    for i in users_object:
        data.update({
            i.id:{
                "username":i.username,
                "password":i.password,
                "id":i.id,
            }
        })
    data = {"data":data}
    return render(request,"delete_user.html",data)

def delete_user(request):
    user = User.objects.get(id=request.POST["id"])
    user.delete()

    users_object = User.objects.all()
    data = dict()
    for i in users_object:
        data.update({
            i.id: {
                "username": i.username,
                "password": i.password,
                "id": i.id,
            }
        })
    data = {"data": data}
    return render(request, "delete_user.html", data)

        Routing code:

from testqing.views import *

urlpatterns = [
    path('delete/user/',delete_user),
    path('delete/',get_delete_user),
]

        Template code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>QingAn</title>
</head>
<body>

    <table>
        <tr>
            <th>ID</th>
            <th>username</th>
            <th>password</th>
        </tr>
        {% for d in data.values %}
            <tr>
                <form action="/delete/user/" method="post">
                    <input type="hidden" name="id" value="{{ d.id }}">
                    <td>
                        <input type="text" name="username" value="{{d.username }}">
                    </td>
                    <td>
                        <input type="password" name="password" value="{{d.password }}">
                    </td>
                    <td>
                        <input type="submit" value="delete">
                    </td>
                </form>
            </tr>
        {% endfor %}
    </table>

</body>
</html>

        The effect is similar to that of the modified interface, but the function is different. Please try it yourself.

Tags: Python Django

Posted on Tue, 09 Nov 2021 22:29:39 -0500 by Runnion