超级用户可视化编辑数据库

一、超级用户的建立

python manage.py createsuperuser

进入后台,管理后台模块功能不止管理用户,还可以管理全部应用项目(app)的模型。

二、将pollsapp应用的模型加入后台模块

就是将pollsapp应用模块注册到管理后台admin.py模块中。(pollsapp应用下的admin.py也是空文件)

from django.contrib import admin
# Register your models here.
from .models import Question

admin.site.register(Question)  #register登记

三、将数据库应用的视图模块,显示出来

from django.http import HttpResponse
from .models import Question  #导入Question模型

def index(request):
    latest_question_list = Question.objects.order_by('pub_date')[:5] #获取基于字段pub_date排序的数据列表latest_question_list
    output = '<br>'.join([q.question_text for q in latest_question_list])
    return HttpResponse("This is pollsapp index page!<br><br>"+output)

四、使用模板优化视图

在pollsapp目录中,新建一个名称为templates子目录,然后再该子目录下再新建一个名为pollsapp的二级子目录(Django建议与应用名称一致),在该目录下创建一个名为index.html的HTML模板。

目录为 pollsapp\templates\pollsapp\index.html

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

    <h3>Latest Question List</h3>
    {% if latest_question_list %}
{# {% if %}是条件语句,判断latest_question_list时候为空#}
    <ul>
        {% for question in latest_question_list %} {# {% for %}是循环语句,获取latest_question_list列表中每一项内容#}
        <li>
            <a href="/pollsapp/{{ question.id }}/">{{ question.question_text }}</a>
        </li>
        {% endfor %}
    </ul>
    {% else %}
        <p>No polls are available.</p>
    {% endif %}
</body>
</html>

五、重新改写视图文件view.py,将HTML应用进去

from django.http import HttpResponse
from .models import Question  #导入Question模型
from django.template import loader

def index(request):
    latest_question_list = Question.objects.order_by('pub_date')[:5] #获取基于字段pub_date排序的数据列表latest_question_list
    template = loader.get_template('pollsapp/index.html') #通过loader对象调用get_template()方法,加载了视图的HTML模板。
    context = {
        'latest_question_list' : latest_question_list, #这个地方字典的key必须是变量名加引号,不一致出错。
    }
    return HttpResponse(template.render(context,request))#通过template对象调用render()方法,将内容参数context渲染到HTML模板中。

 其实就是先把HTML模板灌入template,再利用render函数带入内容字典,字典中的数据就会自动替换掉模板中的变量。

posted @ 2023-04-05 23:25  老人与小孩  阅读(12)  评论(0编辑  收藏  举报