6 URL 实习文章链接跳转

 

 

 

 需要解决的三个问题?

.

 



 

 

 

1.不够多的URL

  (1)正则表达式

 

 

  (2)\d 数字

/detail/123

/detail/(\d){3}  #限定3个数字

/detail/(\d+)   #限定多个数字

 

  (3)修改url

url(r'^detail/(?P<page_num>\d+)$', detail,name='detail'),

  

  • 给数字起个名字: page_num

 

 

  (4)修改view视图文件:#取出id为page_num这篇文章

 

def detail(request,page_num):
    """创建评论视图"""
    if request.method == 'GET':
        form = CommentForm() #实例化一个表单
    if request.method == 'POST':
        form = CommentForm(request.POST)  #提交数据
        print(form)
        if form.is_valid():       #判断表单的数据是否通过验证;
            print(form.is_valid)  #返回布尔值,True 或者False
            print(form.cleaned_data)
            name = form.cleaned_data['name']
            comment = form.cleaned_data['comment']
            c = Comment(name=name,comment=comment)  #把数据储存到Comment模型的实例c中
            c.save()  #保存到数据库
            return redirect(to='detail')

    context ={}
    comment_list = Comment.objects.all()   #获取comment评论的所有数据
    article = Article.objects.get(id=page_num)  #取出id为page_num这篇文章
    context['article'] = article
    context['comment_list'] = comment_list
    context['form'] = form
    # print('11111')  for testing
    # print(form.errors)
    # print('2222')
    # print(form)

    comment_page = render(request,'article-detail.html',context)  #render函数
    return comment_page
View Code

 

 

   (5)详情页article-tail.html:替换数据库中捕获到的特定文章

        <div class="ui  segment padded container" >
            <h1 class="ui header" style="font-family:'Oswald', sans-serif;font-size:40px">
                {{ article.headline }}
            </h1>
            <p>
                {{ article.content }}
            </p>
        </div>
View Code

 

 

  (6)如何跳转?修改fires_web.html的a标签 

  • 文章标题  设置跳转
  • readmore  设置跳转

 

                <a href="{% url 'detail' article.id %}">
                    <h2 class="ui header">
                        {{ article.headline }}
                    </h2>
                </a>

                <a href="{% url 'detail' article.id %}">
                        <i class="angle tiny double grey right icon">READMORE</i>
                </a>

 

 

 

  (7)查看效果

    

    

    

     

     

 

2.怎么让评论只属于一篇文章

  (1)数据库对应关系

  • 一对多:一辆车--4个轮子

  

  • 多对一

  

  • 一对一:一辆车:一个引擎

    

  • 多对多:一个人可以购买多辆车;一辆车可以被多个人驾驶

    

 

  (2)文章,评论  :1对多关系

  • django中只有一对一,多对一,多对多关系
  • 实现一对多,可以反过来实现多对一
  • 一篇博客可以对应多个评论
  • 反过来在评论里实现
外键

belong_to = models.ForeignKey(to=Aritcle, related_name='under_comments',null=True,blank=True)

  

  

  

     

 

 

   (3)查询数据,数据装载到context中

  两个方法

  1. Article模型中查出我想要的数据:普通评论
  2. Comment模型中查出 :最佳评论

 

  (4)第一种方法:普通评论查找; Article模型

  

 

  •   article-tail.html 通过传入的  article 查找数据

    

    

 

 

  •    查看评论,admin后台修改评论的 belong to字段

 

    

 

 

 

 

 

  (6) 第二种:最优评论,comment模型中查找数据

  •   Model层:添加最优评论字段,布尔值,默认false
best_comment = models.BooleanField(default=False)  #最优评论字段布尔值

  

 

  •   更新数据库,后台查看

  • view视图,查找最优评论;best_comment返回的是list列表

 

 

 

  • 判断最优评论是否返回,取第一个评论

 

from django.shortcuts import render,HttpResponse,redirect
from firstapp.models import People,Aritcle,Comment
from django.template import Context,Template
from firstapp.form import CommentForm



def first_try(request):
    person = People(name='alxe',job='it')
    html_string = '''
                <!DOCTYPE html>
                <html>
                  <head>
                    <meta charset="utf-8">
                    <title>first_try</title>
                  </head>
                  <body>
                    <h1>Hello</h1>
                    <h3> {{ person.name }} </h3>
                  </body>
                </html>
    '''
    t = Template(html_string)
    c = Context({'person':person})
    web_page = t.render(c)

    return HttpResponse(web_page)



def index(request):
    print(request)
    print("==="*30)
    print(dir(request))
    print("==="*30)
    print(type(request))

    queryset = request.GET.get('tag')
    print(queryset)

    if queryset:
        article_list = Aritcle.objects.filter(tag=queryset)  #过滤器
    else:
        article_list = Aritcle.objects.all()  #获取Article数据库所有的数据

    context = {}
    context['article_list'] = article_list
    index_page = render(request,'firstweb.html',context)
    return index_page

def detail(request,page_num):
    """创建评论视图"""
    if request.method == 'GET':
        form = CommentForm() #实例化一个表单
    if request.method == 'POST':
        form = CommentForm(request.POST)  #提交数据
        print(form)
        if form.is_valid():       #判断表单的数据是否通过验证;
            print(form.is_valid)  #返回布尔值,True 或者False
            print(form.cleaned_data)
            name = form.cleaned_data['name']
            comment = form.cleaned_data['comment']
            c = Comment(name=name,comment=comment)  #把数据储存到Comment模型的实例c中
            c.save()  #保存到数据库
            return redirect(to='detail')

    context ={}
    #最优评论
    a = Aritcle.objects.get(id=page_num)      #查找出该文章的id号
    best_comment = Aritcle.objects.filter(best_comment=True, belong_to=a)  #best_comment返回的是list列表
    #select *from where best_comment=True and belong_to=a
    if best_comment:
        context['best_comment'] = best_comment[0]

    
    article = Aritcle.objects.get(id=page_num)  #取出id为page_num这篇文章
    context['article'] = article
    context['form'] = form
    comment_page = render(request,'article-detail.html',context)  #render函数
    return comment_page

    #comment_list = Comment.objects.all()   #获取comment评论的所有数据

    #context['comment_list'] = comment_list

    # print('11111')  for testing
    # print(form.errors)
    # print('2222')
    # print(form)
View Code

 

 

  •  Template层:
  • 1.添加best_comment

    

  • 2.修饰

 

                  <div class="ui label">
                    <i class="icon fire">BEST</i>   #添加label标签
                  </div>
  <div class="ui divider"></div>  #添加隔离直线

  

 

 

                  <div class="ui mini red left ribbon label">
                    <i class="icon fire">BEST</i>
                  </div>

  

 

 

  •  3.提交评论:错误
  • 第一个错误:redirect 缺少参数 page_num
  • 第二个错误:对应的article也要存储到comment

  

 

  • 4.redirect添加参数

 

         

 

  •  5,article的id存储到Comment中

  

 

     

 

def detail(request,page_num):
    """创建评论视图"""
    if request.method == 'GET':
        form = CommentForm() #实例化一个表单
    if request.method == 'POST':
        form = CommentForm(request.POST)  #提交数据
        print(form)
        if form.is_valid():       #判断表单的数据是否通过验证;
            print(form.is_valid)  #返回布尔值,True 或者False
            print(form.cleaned_data)
            name = form.cleaned_data['name']
            comment = form.cleaned_data['comment']
            a = Aritcle.objects.get(id=page_num)      #查找出该文章的id号
            c = Comment(name=name,comment=comment, belong_to=a)  #把数据储存到Comment模型的实例c中
            c.save()  #保存到数据库
            return redirect(to='detail', page_num=page_num)

    context ={}
    #最优评论
    a = Aritcle.objects.get(id=page_num)      #查找出该文章的id号
    best_comment = Comment.objects.filter(best_comment=True, belong_to=a)  #best_comment返回的是list列表
    #select *from where best_comment=True and belong_to=a
    if best_comment:
        context['best_comment'] = best_comment[0]



    article = Aritcle.objects.get(id=page_num)  #取出id为page_num这篇文章
    context['article'] = article
    context['form'] = form
    comment_page = render(request,'article-detail.html',context)  #render函数
    return comment_page
View Code

 

 

 

 

 

 3.分离视图

 

  (1)分离视图,加载文章内容和评论

 

 

   (2)分视图:post提交表单评论

 

 

def detail(request, page_num):
    """加载文章,评论视图"""
    context ={}
    form = CommentForm
    a = Aritcle.objects.get(id=page_num)      #最优评论  #查找出该文章的id号
    best_comment = Comment.objects.filter(best_comment=True, belong_to=a)  #best_comment返回的是list列表
                                                                        #select *from where best_comment=True and belong_to=a
    if best_comment:
        context['best_comment'] = best_comment[0]

    article = Aritcle.objects.get(id=page_num)  #取出id为page_num这篇文章
    context['article'] = article
    context['form'] = form
    comment_page = render(request,'article-detail.html',context)  #render函数
    return comment_page

def detail_comment(request, page_num):
    """post方法form表单提交"""
    form = CommentForm(request.POST)  #提交数据
    print(form)
    if form.is_valid():       #判断表单的数据是否通过验证;
                                            #print(form.is_valid)  #返回布尔值,True 或者False
                                            #print(form.cleaned_data)
        name = form.cleaned_data['name']
        comment = form.cleaned_data['comment']
        a = Aritcle.objects.get(id=page_num)      #查找出该文章的id号
        c = Comment(name=name,comment=comment, belong_to=a)  #把数据储存到Comment模型的实例c中
        c.save()  #保存到数据库
    return redirect(to='detail', page_num=page_num)
View Code

 

 

  (3)添加url

    url(r'^detail/(?P<page_num>\d+)/comment$',detail_comment,name='comment'),

  

 

 

  (4)Template层:添加action

  此处的comment是name=comment

        <form class="ui error tiny form" action="{% url 'comment' article.id %}" method="post">

  

 

 

 

 

   (5)错误信息没有打印

  

 

posted @ 2017-12-23 19:09  venicid  阅读(515)  评论(0编辑  收藏  举报