四、视图与模板

当前目录框架

 

 

一、model与view结合

1、在view导入model:打开message/views.py

from django.shortcuts import render
from django.http import HttpResponse
import time
import hashlib
from apps.message.models import *

# Create your views here.

def AXB_bd(request):
    return HttpResponse("响应成功")

def AXB_bind_id(request):
    to = token.objects.filter(id=1)
    return HttpResponse(to)

  

2、链接带url:打开message/urls.py

from django.urls import path
from apps.message import views


urlpatterns = [
    path('', views.AXB_bd, name='AXB_bd'),
    path('bind/',views.AXB_bind_id, name='bind_id')
]

 

访问接口:http://127.0.0.1:8000/message/bind/

 

 响应成功

 

 

二、模板

1、创建基础模板

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

{% if token_list %}
    <ul>
    {% for token in token_list %}
        <li><a href="{% url 'message:bind_id' %}">{{ token }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No token are available.</p>
{% endif %}

</body>
</html>

 放在图中目录下

 

 

 

打开message/views视图输入

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from apps.message.models import *

# Create your views here.

def AXB_bd(request):
    to = token.objects.filter(id=1)
    return HttpResponse(to)

def AXB_bind_id(request):
    to = token.objects.filter(id=1)
    bind = loader.get_template('message/bind.html')

    context = {
        'token_list':to
    }
    # return HttpResponse(bind.render(context, request))
    return render(request, 'message/bind.html', context)

 

优化url:打开message/urls输入

from django.urls import path
from apps.message import views

app_name = 'message'
urlpatterns = [
    path('', views.AXB_bd, name='AXB_bd'),
    path('bind/',views.AXB_bind_id, name='bind_id')
]

 

启动访问成功

 

posted @ 2020-11-14 19:15  冯立挺  阅读(107)  评论(0编辑  收藏  举报