M
创建评论模型
from django.db import models
# Create your models here.
class People(models.Model):
name = models.CharField(null=True, blank=True,max_length=200)
job = models.CharField(null=True, blank=True, max_length=200)
def __str__(self):
return self.name
class Aritcle(models.Model):#新增
headline = models.CharField(null=True, blank=True,max_length=500)#新增
content = models.TextField(null=True, blank=True)#新增
TAG_CHOICES = (
('tech', 'Tech'),
('life','Life'),
)
tag = models.CharField(null=True, blank=True, max_length=5, choices=TAG_CHOICES)
def __str__(self):
return self.headline
class Comment(models.Model):#1
name = models.CharField(null=True, blank=True, max_length=50)#1
comment = models.TextField()#1
def __str__(self):#1
return self.comment#1
迁移合并数据库
python manage.py makemigrations
python manage.py migrate
V
from django.shortcuts import render, HttpResponse, redirect
from firstapp.models import Aritcle, Comment#2
from django.template import Context, Template
from firstapp.form import CommentForm
# Create your views here.
def index(request):
print(request)
print('==='*30)
print(dir(request))
print('==='*30)
print(type(request))
queryset = request.GET.get('tag')
if queryset:
article_list = Aritcle.objects.filter(tag=queryset)
else:
article_list = Aritcle.objects.all()#变量article_list储存Article所有的文章
context = {}#新建字典
context['article_list'] = article_list #字典context中的article_list键(html中通过检索键提取文章内容)对应article_list变量的值
index_page = render(request, 'first_web_2.html', context)
return index_page
def detail(request):
if request.method == 'GET':
form = CommentForm
#HttpRequest对象request的method属性:表示提交请求使用的HTTP方法。它总是大写的。
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
c = Comment(name=name, comment=comment)
c.save()
return redirect(to='detail')
context = {}
comment_list = Comment.objects.all()
context['comment_list'] = comment_list
context['form'] = form
return render(request, 'article_detail.html', context)
HttpRequest对象的属性
path属性
表示提交请求页面完整地址的字符串,不包括域名
如”/music/bands/the_beatles/”。
method属性
表示提交请求使用的HTTP方法。它总是大写的。例如:
if request.method == ‘GET’:
do_something()
elif request.method == ‘POST’:
do_something_else()
GET属性
一个类字典对象,包含所有的HTTP的GET参数的信息。见 QueryDict文档。
POST属性
一个类字典对象,包含所有的HTTP的POST参数的信息。见 QueryDict文档。
通过POST提交的请求有可能包含一个空的 POST字典,也就是说, 一个通过POST方法提交的表单可能不包含数据。因此,不应该使用ifrequest.POST 来判断POST方法的使用,而是使用