[项目1] bloger - day1
阅读原文时间:2023年07月14日阅读:3

项目代码:https://github.com/venicid/Project1--Bloger

  1.创建project

PS C:\Users\Administrator\Desktop\bloger> django-admin startproject bloger

  2 创建app

PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py startapp firstapp

  3 setting添加app

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstapp',
]

  4 更新数据库表

PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations

No changes detected
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py migrate

  5 运行runserver

PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py runserver

  6 创建超级管理员

PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py createsuperuser
Username (leave blank to use 'administrator'): adminuser
Email address:
Password:
Password (again):
Superuser created successfully.

  

  1  Model层:

from django.db import models

Create your models here.

class Article(models.Model):
"""博客内容字段"""
title = models.CharField(null=True, blank=True, max_length=) #文章标题
content = models.TextField(null=True, blank=True) #文章内容

def \_\_str\_\_(self):  
    return self.title

   admin 注册

from django.contrib import admin
from firstapp.models import Article

Register your models here.

admin.site.register(Article)

  合并数据库

PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations
Migrations for 'firstapp':
0001_initial.py:
- Create model Article
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py migrate

  runserver

    

  添加数据

    

 2 View层

  1 获取Article表的所有数据 article_list = Article.objects.all()

from django.shortcuts import render,redirect
from firstapp.models import Article

Create your views here.

def index(request):
"""主页视图"""
context = {}
article_list = Article.objects.all() # 获取Article表的所有数据
context['article_list'] = article_list
return render(request, 'index.html', context)

 3 T层

  1 导入静态文件,页面

    

  2 setting设置

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates').replace('\\','/')],

{% load staticfiles %}

<link rel="stylesheet" href="{% static 'css/semantic.css' %}" media="screen" title="no title" charset="utf-8">  
<link rel="stylesheet" href="{% static 'css/list\_custom.css' %}" media="screen" title="no title" charset="utf-8">

<img src="{% static 'images/tenlogo.png' %}" alt="">

  3 渲染目标语言

      {% for article in article\_list  %}

        <div class="column">  
            <a class="ui fluid card" href="#detail/215">  
                <div class="image">  
                    <img src="{% static 'images/img1.jpg' %}" alt="" style="height:200px;object-fit: cover;">  
                </div>  
            </a>

            <div class="title header" href="/detail/215">{{ article.title }}</div>

            <i class="icon grey unhide"></i>  
            <span style="color:#bbbbbb">10K</span>  
            <span class="" style="color:rgb(226, 226, 226)">|</span>  
            <i class="icon grey checkmark"></i>  
            <span style="color:#bbbbbb">  people got it</span>

        </div>

      {% endfor %}

  4 配置 url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
]

  

  5 过滤器

    {{ article.content|truncatechars: }} #过滤器:100个字符

1 M层

    1 tag标签

from django.db import models

Create your models here.

class Article(models.Model):
"""博客内容字段"""
title = models.CharField(null=True, blank=True, max_length=) #文章标题
content = models.TextField(null=True, blank=True) #文章内容

TAG\_CHOICES = (  
    ('cry','悬疑类型'),  
    ('ai','科幻类型'),  
    ('life','生活类型')  
    )  
tag = models.CharField(null=True, blank=True, max\_length=, choices=TAG\_CHOICES)

def \_\_str\_\_(self):  
    return self.title

  2 数据库注册,合并数据

  3 admin后台

    

2 View层

def index(request):
"""主页视图"""
queryset = request.GET.get('tag')
if queryset:
article_list = Article.objects.filter(tag=queryset) #过滤器
else:
article_list = Article.objects.all() # 获取Article表的所有数据

context = {}  
context\['article\_list'\] = article\_list  
return render(request, 'index.html', context)

3 T 层

全部

悬疑

    <div class="ui container nav">  
        <div class="ui  text four item menu ">  
            <a class="item" href="http://127.0.0.1:8000/index/">全部</a>  
            <a class="item" href="?tag=ai">AI</a>  
            <a class="item" href="?tag=linux">Linux</a>  
            <a class="item" href="?tag=python">Python</a>  
        </div>  
    </div>

                <div class="ui mini tag label">  
                    {{ article.tag }}  
                </div>

  

1.Model层:

不变

2 View层

article = Article.objects.get(id=page_num) #取出id为1的这篇文章

from django.shortcuts import render,redirect
from firstapp.models import Article

Create your views here.

def index(request):
"""主页视图"""
context = {}
article_list = Article.objects.all() # 获取Article表的所有数据
context['article_list'] = article_list
return render(request, 'index.html', context)

def detail(request,page_num):
"""detail视图"""
context = {}
article = Article.objects.get(id=page_num) #取出id为1的这篇文章
context['article'] = article
return render(request, 'detail.html', context)

  url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index,detail

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
url(r'^detail/(?P\d+)$', detail, name='detail'),
]

 3 T层

{% load staticfiles %}


渲染模板语言

      <h1 class="ui header">{{ article.title }}</h1>  
        <p>  
            {{ article.content }}  
        </p>

全部

  

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

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

{{ article.title }}

1 M层

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

from django.db import models

Create your models here.

class Article(models.Model):
"""博客内容字段"""
title = models.CharField(null=True, blank=True, max_length=) # 文章标题
content = models.TextField(null=True, blank=True) # 文章内容
TAG_CHOICES = (
('ai', 'ai'),
('python', 'python'),
('linux', 'linux'),
)
tag = models.CharField(null=True, blank=True, max_length=, choices=TAG_CHOICES)

def \_\_str\_\_(self):  
    return self.title

class Comment(models.Model):
"""评论字段表"""
name = models.CharField(null=True, blank=True, max_length=)
comment = models.TextField(null=True, blank=True)
belong_to = models.ForeignKey(to=Article, related_name='under_comments', null=True, blank=True)

def \_\_str\_\_(self):  
    return self.comment

  2 注册

from django.contrib import admin
from firstapp.models import Article,Comment

Register your models here.

admin.site.register(Article)
admin.site.register(Comment)

3  合并数据库

PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations
No changes detected
PS C:\Users\Administrator\Desktop\bloger> python.exe .\manage.py makemigrations

2 V 层

  不变

def detail(request,page_num):
"""加载文章,评论视图"""
context = {}
article = Article.objects.get(id=page_num) #取出id为1的这篇文章
context['article'] = article
return render(request, 'detail.html', context)

url 不变

3  T层

通过Article的字段under_comments查找评论

{% for comment in article.under\_comments.all  %}  
            <div class="comment">  
                <div class="avatar">  
                    <img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />  
                </div>  
                <div class="content">  
                    <a href="#" class="author">{{ comment.name }}</a>  
                    <div class="metadata">  
                        <div class="date">2 days ago</div>  
                    </div>  
                    <p class="text" style="font-family: 'Raleway', sans-serif;">  
                        {{ comment.comment }}  
                    </p>  
                </div>  
            </div>  
      {% endfor %}

  

1  M层:不变

2  V层

  1 定义Django表单

from django import forms

class CommentForm(forms.Form):
"""定义Django自带的form表单"""
name = forms.CharField(max_length=)
comment = forms.CharField(widget=forms.Textarea)

  2  get实例化一个表单

      post提交表单数据

from django.shortcuts import render,redirect
from firstapp.models import Article,Comment
from django import forms

class CommentForm(forms.Form):
"""定义个Django自带的表单类"""
name = forms.CharField(max_length=50)
comment = forms.CharField()

def detail(request,page_num):
"""加载文章,评论视图"""
if request.method == 'GET':
form = CommentForm #实例化表单

if request.method == 'POST':  
    form = CommentForm(request.POST)  #提交数据  
    # print(form) for testing  
    if form.is\_valid():   #判断表单的数据是否通过验证  
        name = form.cleaned\_data\['name'\]  
        comment = form.cleaned\_data\['comment'\]  
        a = Article.objects.get(id=page\_num)   #查找出该文章对应的id  
        c = Comment(name=name, comment=comment, belong\_to=a)    #写评论  
        c.save()   #保存数据库  
        return redirect(to='detail',page\_num=page\_num)  #重定向本页

context = {}  
article = Article.objects.get(id=page\_num)  #取出id为1的这篇文章  
context\['article'\] = article  
context\['form'\] = form  
return render(request, 'detail.html', context)

  url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index, detail

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
url(r'^detail/(?P\d+)$',detail,name='detail'),
]

 3 T层

    <form class="ui form" action="" method="post">

        {{ form.as\_p }}  
        {% csrf\_token %}  
        <button type="submit" class="ui blue button" >Click</button>  
    </form>

  

1  form表单单独写成文件

      

      

        

2.各种验证器

from django import forms
from django.core.exceptions import ValidationError

def words_validator(comment):
"""验证器函数"""
if len(comment) < :
raise ValidationError('内容长度不足5个字符')

def comment_validator(comment):
"""过滤器"""
if '?' in comment:
raise ValidationError('不能包含这个字符')

class CommentForm(forms.Form):
"""定义Django自带的form表单"""
name = forms.CharField(max_length=,
error_messages={
'required': '请输入内容',
},
)

comment = forms.CharField(              # 修改表单样式  
    widget=forms.Textarea,  
    error\_messages={  
        'required':'请输入内容',  
        },  
    validators=\[words\_validator,comment\_validator\]  
    )

    

  1 sematic ui 的表单

        <form class="ui form" action="" method="post">

            <div class="field">  
                <label> name</label>  
                <input type="text" name="name" value="">  
            </div>  
            <div class="field">  
                <label>comment</label>  
                <textarea></textarea>  
            </div>

            <button type="submit" class="ui blue button" >Click</button>  
        </form>

  • 请输入内容

  • 请输入内容

  2 错误表单

  

  3.post传到后台的数据

    

    

4.定制错误表单

      <form class="ui error tiny form" action="" method="post">

          {% if form.errors %}  
              <div class="ui error message">  
                {{ form.errors }}  
              </div>  
              {% for field in form  %}  
                <div class="{{ field.errors|yesno:'error, ' }} field">  
                  {{ field.label }}  
                  {{ field }}  
                </div>  
              {% endfor %}

          {% else %}  
              {% for field in form  %}  
                <div class="field">  
                  {{ field.label }}  
                  {{ field }}  
                </div>  
              {% endfor %}  
          {% endif %}  
          {% csrf\_token %}  
            <button type="submit" class="ui blue button" >Click</button>  
        </form>

        

1 M层

2 V层

1.视图1  加载文章,评论视图

def detail(request,page_num, error_form=None):
"""加载文章,评论视图"""
form = CommentForm # 实例化表单

context = {}  
article = Article.objects.get(id=page\_num)  # 取出id为1的这篇文章  
context\['article'\] = article

if error\_form is not None:  
    context\['form'\] = error\_form  
else:  
    context\['form'\] = form  
return render(request, 'detail.html', context)

  视图 2  post提交评论

def detail_comment(request,page_num):
"""post提交评论"""
form = CommentForm(request.POST) # 提交数据
print(form)
if form.is_valid(): # 判断表单的数据是否通过验证
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
a = Article.objects.get(id=page_num) # 查找出该文章对应的id
c = Comment(name=name, comment=comment, belong_to=a) # 写评论
c.save() # 保存数据库
else:
return detail(request, page_num, error_form=form)

return redirect(to='detail',page\_num=page\_num)  # 重定向本页

2.对应url

from django.conf.urls import url
from django.contrib import admin
from firstapp.views import index,detail,detail_comment

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', index, name='index'),
url(r'^detail/(?P\d+)$',detail,name='detail'),
url(r'^detail/(?P\d+)/detail_comment$', detail_comment, name='detail_comment'),
]

3 T层

  

{% if form.errors %}
{{ form.errors }}
{% for field in form %}
{{ field.label }} {{ field }}
{% endfor %} {% else %} {% for field in form %}
{{ field.label }} {{ field }}
{% endfor %} {% endif %} {% csrf\_token %}

    

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

  •   Model层:添加最优评论字段,布尔值,默认false

class Comment(models.Model):
"""评论字段表"""
name = models.CharField(null=True, blank=True, max_length=)
comment = models.TextField(null=True, blank=True)
belong_to = models.ForeignKey(to=Article, related_name='under_comments', null=True, blank=True)
best_comment = models.BooleanField(default=False) # 最优评论字段布尔值

def \_\_str\_\_(self):  
    return self.comment

  更新数据库,后台

    

  2 V层

def detail(request,page_num, error_form=None):
"""加载文章,评论视图"""
form = CommentForm # 实例化表单

context = {}  
article = Article.objects.get(id=page\_num)  # 取出id为1的这篇文章  
context\['article'\] = article

# 加载最优评论  
a\_id = Article.objects.get(id=page\_num)   # 查找id为1的这个文章  
best\_comment = Comment.objects.filter(best\_comment=True, belong\_to=a\_id)   # 返回这个文章的最优评论  
if best\_comment:  
    context\['best\_comment'\] = best\_comment\[\]

if error\_form is not None:  
    context\['form'\] = error\_form  
else:  
    context\['form'\] = form  
return render(request, 'detail.html', context)

3 T层

{% if best\_comment %}
BEST
{{ best\_comment.name }}

{{ best\_comment.comment }}

{% endif %}
{% for comment in article.under\_comments.all %}
{{ comment.name }}

{{ comment.comment }}

{% endfor %}