第二十 BBS

Posted ckl893

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第二十 BBS相关的知识,希望对你有一定的参考价值。

 1.创建新项目

2.数据表设计

2.1.表结构规划

https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.clean

from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
import datetime
# Create your models here.

class Article(models.Model):
    #文章标题
    title = models.CharField(max_length=255)
    #文章简介
    brief = models.CharField(null=True,blank=True,max_length=255)
    #文章板坏
    category = models.ForeignKey("Category")
    #文章内容
    content = models.TextField("文章内容")
    #作者
    author = models.ForeignKey("UserProfile")
    #文章发布时间,auto_now_add自动发布为发布时的时间
    pub_date = models.DateTimeField(blank=True,null=True)
    #最后修改时间为修改的当前时间
    last_modify = models.DateTimeField(auto_now=True)
    #文章置顶,默认是1000
    priority = models.IntegerField("优先级",default=1000)
    #文章状态可选项
    status_choice = ((\'draft\',"草稿"),
                     (\'published\',"已发布"),
                     (\'hidden\',\'隐藏\'),
                     )
    #文章状态
    status = models.CharField(choices=status_choice,default=\'published\',max_length=64)

    def __str__(self):
        return self.title
    def clean(self):
        # Don\'t allow draft entries to have a pub_date.
        if self.status == \'draft\' and self.pub_date is not None:
            raise ValidationError((\'Draft entries may not have a publication date.\'))
        # Set the pub_date for published items if it hasn\'t been set already.
        if self.status == \'published\' and self.pub_date is None:
            self.pub_date = datetime.date.today()

class Comment(models.Model):
    #关联所属文章
    article = models.ForeignKey(Article,verbose_name="所属文章")
    #顶级评论
    parent_comment = models.ForeignKey(\'self\',related_name=\'my_children\',null=True)
    #评论及点赞可选项
    comment_choice = ((1,\'评论\'),
                    (2,\'点赞\'))
    #评论类型
    comment_type = models.IntegerField(choices=comment_choice,default=1)
    #评论用户
    user = models.ForeignKey("UserProfile")
    #评论内容
    comment = models.TextField(blank=True,null=True)
    # 添加评论时间
    date = models.DateField(auto_now_add=True)

    def __str__(self):
        return "%s,%s,%s" %(self.article,self.comment,self.date)
    def clean(self):
        if self.comment_type == 1 and self.comment is None:
            raise ValidationError("评论写点什么吧")


class Category(models.Model):
    #板块名
    name = models.CharField(max_length=64,unique=True)
    #板块简介
    brief = models.CharField(null=True,blank=True,max_length=255)
    #顶级菜单
    set_as_top_menu = models.BooleanField(default=False)
    #版主设置,可设置为空
    admins = models.ManyToManyField("UserProfile",blank=True)
    #菜单位置
    position_index = models.SmallIntegerField()

    def __str__(self):
        return self.name

class UserProfile(models.Model):
    #关联到django的的User
    user = models.OneToOneField(User)
    #用户名
    name = models.CharField(max_length=32)
    #个人签名
    signature = models.CharField(max_length=255,blank=True,null=True)
    #头像
    head_img = models.ImageField(height_field=200,width_field=200)

    def __str__(self):
        return self.name

2.2.生成表

 3.注册django admin

from django.contrib import admin
from bbs import models
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
    list_display = (\'title\',\'category\',\'author\',\'pub_date\',\'last_modify\',\'status\',\'priority\')

class CommentAdmin(admin.ModelAdmin):
    list_display = (\'article\',\'parent_comment\',\'comment_type\',\'comment\',\'user\',\'date\')

class CategoryAdmin(admin.ModelAdmin):
    list_display = (\'name\',\'set_as_top_menu\',\'position_index\')

admin.site.register(models.Article,ArticleAdmin)
admin.site.register(models.Comment,CommentAdmin)
admin.site.register(models.UserProfile)
admin.site.register(models.Category,CategoryAdmin)

4.添加超级用户

 5.登录添加内容

5.1.添加文章

5.2.添加评论

5.3.为文章添加图片

5.3.1.最新表结构

from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
import datetime
# Create your models here.

class Article(models.Model):
    #文章标题
    title = models.CharField(max_length=255)
    #文章简介
    brief = models.CharField(null=True,blank=True,max_length=255)
    #文章板坏
    category = models.ForeignKey("Category")
    #文章内容
    content = models.TextField("文章内容")
    #作者
    author = models.ForeignKey("UserProfile")
    #文章发布时间,auto_now_add自动发布为发布时的时间
    pub_date = models.DateTimeField(blank=True,null=True)
    #最后修改时间为修改的当前时间
    last_modify = models.DateTimeField(auto_now=True)
    #文章置顶,默认是1000
    priority = models.IntegerField("优先级",default=1000)
    # 文图
    head_img = models.ImageField("文章配图")
    #文章状态可选项
    status_choice = ((\'draft\',"草稿"),
                     (\'published\',"已发布"),
                     (\'hidden\',\'隐藏\'),
                     )
    #文章状态
    status = models.CharField(choices=status_choice,default=\'published\',max_length=64)

    def __str__(self):
        return self.title
    def clean(self):
        # Don\'t allow draft entries to have a pub_date.
        if self.status == \'draft\' and self.pub_date is not None:
            raise ValidationError((\'Draft entries may not have a publication date.\'))
        # Set the pub_date for published items if it hasn\'t been set already.
        if self.status == \'published\' and self.pub_date is None:
            self.pub_date = datetime.date.today()

class Comment(models.Model):
    #关联所属文章
    article = models.ForeignKey(Article,verbose_name="所属文章")
    #顶级评论
    parent_comment = models.ForeignKey(\'self\',related_name=\'my_children\',null=True,blank=True)
    #评论及点赞可选项
    comment_choice = ((1,\'评论\'),
                    (2,\'点赞\'))
    #评论类型
    comment_type = models.IntegerField(choices=comment_choice,default=1)
    #评论用户
    user = models.ForeignKey("UserProfile")
    #评论内容
    comment = models.TextField(blank=True,null=True)
    # 添加评论时间
    date = models.DateField(auto_now_add=True)

    def __str__(self):
        return "%s,%s,%s" %(self.article,self.parent_comment,self.comment)
    def clean(self):
        if self.comment_type == 1 and len(self.comment) == 0:
            raise ValidationError("评论写点什么吧")


class Category(models.Model):
    #板块名
    name = models.CharField(max_length=64,unique=True)
    #板块简介
    brief = models.CharField(null=True,blank=True,max_length=255)
    #顶级菜单
    set_as_top_menu = models.BooleanField(default=False)
    #版主设置,可设置为空
    admins = models.ManyToManyField("UserProfile",blank=True)
    #菜单位置
    position_index = models.SmallIntegerField()

    def __str__(self):
        return self.name

class UserProfile(models.Model):
    #关联到django的的User
    user = models.OneToOneField(User)
    #用户名
    name = models.CharField(max_length=32)
    #个人签名
    signature = models.CharField(max_length=255,blank=True,null=True)
    #头像
    head_img = models.ImageField(height_field=200,width_field=200,blank=True)

    def __str__(self):
        return self.name

5.3.2.重新应用表

5.3.3.添加文章图片

5.3.4.图片默认被保存的路径

5.3.5.图片保存修改

django 自带图片保存,修改字段:

head_img = models.ImageField("文章配图",upload_to="uploads")

上传图片:

自动创建uploads并保存图片

5.4.配置动态板块

5.4.1.配置views

from django.shortcuts import render
from bbs import models

# Create your views here.

def index(request):
#或许所有的的板块 category_list
= models.Category.objects.filter(set_as_top_menu=True).order_by("position_index") return render(request,\'bbs/index.html\',{\'category_list\':category_list})

5.4.2.配置返回页面

返回页面直接配置base即可

https://v3.bootcss.com/examples/navbar-fixed-top/

....
 <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
              {% for category in category_list %}
                    <li class="active"><a href="#">{{ category.name }}</a></li>
              {% endfor %}
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="https://v3.bootcss.com/examples/navbar/">Default</a></li>
            <li><a href="https://v3.bootcss.com/examples/navbar-static-top/">Static top</a></li>
            <li class="active"><a href="https://v3.bootcss.com/examples/navbar-fixed-top/">Fixed top <span class="sr-only">(current)</span></a></li>
          </ul>
        </div><!--/.nav-collapse -->
...

 5.4.3.查看返回板块

5.4.4.增加多的板块

 

 

 5.4.5.配置urls

如果点击板块,只需要返回同一个页面,需要引入一个url,如:http://127.0.0.1:8000/bbs/category/1/

from django.conf.urls import url,include
from bbs import views
urlpatterns = [
    url(r\'^$\', views.index),
    url(r\'category/(\\d+)/$\', views.category),
]

5.4.6.配置views

from django.shortcuts import render
from bbs import models

#单独将category列表取出
category_list = models.Category.objects.filter(set_as_top_menu=True).order_by("position_index")
# Create your views here.

def index(request):
    return render(request,\'bbs/index.html\',{\'category_list\':category_list})

def category(request,id):
    category_obj = models.Category.objects.get(id=id)
    return render(request, \'bbs/index.html\',{\'category_list\':category_list,
                                             \'category_obj\':category_obj})

5.4.7.配置base页面

....
          <ul class="nav navbar-nav">
              {% for category in category_list %}
                  <!-- 如果前端循环的category的id正好和后端返回的id相等,则将当前板块设为active -->
                  {% if category.id == category_obj.id %}
                    <li class="active"><a href="/bbs/category/{{ category.id }}">{{ category.name }}</a></li>
                  {% else %}
                    <li class=""><a href="/bbs/category/{{ category.id }}">{{ category.name }}</a></li>
                  {% endif %}
              {% endfor %}
          </ul>
....

5.4.8.查看返回

 6.配置用户登录及退出

6.1.配置登录及注销方法

from django.shortcuts import render
from bbs import models
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.decorators import login_required
from django.shortcuts import render,HttpResponse,HttpResponseRedirect

category_list = models.Category.objects.filter(set_as_top_menu=True).order_by("position_index")
# Create your views here.

def index(request):
    return render(request,\'bbs/index.html\',{\'category_list\':category_list})

def category(request,id):
    category_obj = models.Category.objects.get(id=id)
    return render(request, \'bbs/index.html\',{\'category_list\':category_list,
                                             \'category_obj\':category_obj})

def acc_login(request):
    if request.method == \'POST\':
        print(request.POST)
        user = authenticate(username=request.POST.get(\'username\'),
                            password=request.POST.get(\'password\'))
        if user is not None:
            login(request,user)
            return HttpResponseRedirect(\'/bbs\')
        else:
            login_err = "Worng user name or password"
            return render(request,\'login.html\',{\'login_err\':login_err})
    return render(request,\'login.html\')

def acc_logout(request):
    logout(request)
    return HttpResponseRedirect(\'/bbs\')

6.2.配置url

from django.conf.urls import url,include
from django.contrib import admin
from bbs import views

urlpatterns = [
    url(r\'^admin/\', admin.site.urls),
    url(r\'^bbs\',include(\'bbs.urls\')),
    url(r\'login\',views.acc_login,name=\'login\'),
    url(r\'logout\',views.acc_logout,name=\'logout\'),
]

6.3.配置返回html

....
      <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
              {% for category in category_list %}
                  <!-- 如果前端循环的category的id正好和后端返回的id相等,则将当前板块设为active -->
                  {% if category.id == category_obj.id %}
                    <li class="active"><a href="/bbs/category/{{ category.id }}">{{ category.name }}</a></li>
                  {% else %}
                    <li class=""><a href="/bbs/category/{{ category.id }}">{{ category.name }}</a></li>
                  {% endif %}
              {% endfor %}
          </ul>
          <ul class="nav navbar-nav navbar-right">
              <!-- 如果用户登录,则显示用户名及注销,否则显示登录 -->
              {% if request.user.is_authenticated %}
                  <li class=""><a href="#">{{ request.user.userprofile.name }}</a></li>
                  <li class=""><a href="{% url \'logout\' %}">注销</a></li>
              {% else %}
                  <li class=""><a href="{% url \'login\' %}">登录/注册</a></li>
              {% endif %}
          </ul>
        </div><!--/.nav-collapse -->
....

登录html 拷贝之前的登录页面

6.4.登录及退出

登录:

7.各个板块分开展示

7.1.每个板块增加文章

 7.2.内容预览

7.2.1.各个专栏展示

7.2.2.全部展示所有的内容

....
def category(request,id):
    category_obj = models.Category.objects.get(id=id)
    if category_obj.position_index == 1:#全部
        article_list = models.Article.objects.filter(status=\'published\')
    else:
        article_list = models.Article.objects.filter(category_id = category_obj.id,status=\'published\')
    return render(request, \'bbs/index.html\',{\'category_list\':category_list,
                                             \'category_obj\':category_obj,
                                             \'article_list\':article_list
                                             })
.....

7.2.3.查看全部内容

7.3.默认路径访问所有内容

如:http://127.0.0.1:8000/bbs

 

def index(request):
    article_list = models.Article.objects.filter(status=\'published\'python自动化开发-[第二十二天]-bbs多级评论点赞上传文件

第二十五课预习任务

(89)Wangdao.com第二十二天_JavaScript DocumentFragment 节点

20-----BBS论坛

javaSE第二十二天

CSDN编程竞赛 ——— 第二十一期