栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django概述(第四章)模版

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django概述(第四章)模版

通过第一章和第三章创建级别目录
所需级别目录

所需代码
注意:所有的html页面都在templates文件夹中
views.py

from django.shortcuts import render,redirect
from django import http
from .models import *
# Create your views here.
def index(request):
    books=Articles.objects.all() #查找所有书籍
    print(books)
    return render(request,"index.html",context={"books":books})
def login(request):
    #数据提交给了login函数
    #用请求的方式分别进行处理
    if request.POST:
        name=request.POST.get("uname")
        pwd=request.POST.get("pwd")
        users=Users.objects.filter(username=name,password=pwd)
        if users:
            return redirect("show/")
        else:
            return http.HttpResponse("用户名或密码错误")
    return render(request,"login.html")

def zhuce(request):
    if request.POST:
        name = request.POST.get("name")
        email = request.POST.get("email")
        pwd = request.POST.get("pwd")
        repwd = request.POST.get("repwd")
        Users.objects.create(username=name,email=email,password=pwd)
        if pwd==repwd:
            return redirect("/")
        else:
            http.HttpResponse("两次密码输入不一致")
    return render(request,"zhuce.html")

urls.py
注意:是应用的urls.py文件

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path('', views.login),
    path('show/', views.index),
    path('zhuce/',views.zhuce),
]

models.py

from django.db import models

# Create your models here.
class Users(models.Model):
    class Meta:
        db_table="users" #描述原数据的内部类
    id=models.AutoField(primary_key=True,db_column="id")
    username = models.CharField(max_length=30)
    email = models.CharField(max_length=50,null=True)
    password = models.CharField(max_length=30,null=True)
    def __str__(self):#魔法函数,用于打印对象时,显示对象中的某个信息
        return self.email

class Articles(models.Model):
    class Meta:
        db_table="articles"
    id=models.AutoField(primary_key=True,db_column="id")
    title=models.CharField(max_length=50,null=True)
    content=models.TextField()
    create_date=models.DateTimeField(null=True,auto_now_add=True)
    user_id=models.ForeignKey(Users,on_delete=models.CASCADE,db_column="user_id")
    def __str__(self):
        return self.title

base.html




    
    Title


{% block content %}
{% endblock %}
注册
登陆


index.html




    
    Title






图书列表

{% for i in books %} {% endfor %}
编号 书名 描述 出版时间 作者
{{i.id}} {{i.title}} {{i.content|truncatewords:2}} {{i.create_date}} {{i.user_id.username}}

login.html

{% extends "base.html" %}
{% block content %}
{% endblock %}}

zhuce.html

{% extends "base.html" %}
{% block content %}
{% endblock %}

结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号