[项目1] bloger - day1

[项目1] bloger - day1,第1张

[项目1] bloger - day1

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

1.准备工作

  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.

  

2.博客主页   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个字符

3 文章分类
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 层

<a class="item" href="{% url 'index' %}">全部</a>

<a class="active item" href="?tag=cry">悬疑</a>

        <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>

  

3.博客详情页 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<page_num>\d+)$', detail, name='detail'),
]
 3 T层
{% load staticfiles %}    

<link rel="stylesheet" href="{% static 'css/semantic.css' %}" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="{% static 'css/detail.css' %}" media="screen" title="no title" charset="utf-8"> <img src="{% static 'images/tenlogo.png' %}" alt="">

渲染模板语言

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

4. 实现跳转功能

<a class="item" href="{% url 'index' %}">全部</a>

  <a href="{% url 'detail' article.id %}">

               <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>
 <title>{{ article.title }}</title>
5.展示这个文章对应的评论 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 %}

  


6 form表单提交评论
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<page_num>\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>

  

7.Django自带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]
)

    

8.定制表单

  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>

<tr><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>请输入内容</li></ul><input id="id_name" maxlength="" name="name" type="text" /></td></tr>
<tr><th><label for="id_comment">Comment:</label></th><td><ul class="errorlist"><li>请输入内容</li></ul><textarea cols="" id="id_comment" name="comment" rows="">
</textarea></td></tr>

  2 错误表单

  

<div class="ui form">
<div class="two fields">
<div class="field error">
<label>First Name</label>
<input placeholder="First Name" type="text">
</div>
<div class="field">
<label>Last Name</label>
<input placeholder="Last Name" type="text">
</div>
</div>
<div class="field error">
<label>Gender</label>
<div class="ui selection dropdown">
<div class="default text">Select</div>
<i class="dropdown icon"></i>
<input type="hidden" name="gender">
<div class="menu">
<div class="item" data-value="male">Male</div>
<div class="item" data-value="female">Female</div>
</div>
</div>
</div>
<div class="inline field error">
<div class="ui checkbox">
<input type="checkbox" tabindex="" class="hidden">
<label>我同意本条款和条件</label>
</div>
</div>
</div>

  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>

        

7. 分类视图 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<page_num>\d+)$',detail,name='detail'),
url(r'^detail/(?P<page_num>\d+)/detail_comment$', detail_comment, name='detail_comment'),
]
3 T层

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

<form class="ui error tiny form" action="{% url 'detail_comment' article.id %}" 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>

    

8.添加最优评论

  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层

 <div class="ui comments">

                    {% if best_comment %}
<div class="ui mini red left ribbon label">
<i class="icon fire">BEST</i>
</div> <div class="best comment">
<div class="avatar">
<img src="http://semantic-ui.com/images/avatar/small/matt.jpg" alt="" />
</div>
<div class="content">
<a href="#" class="author">{{ best_comment.name }}</a>
<div class="metadata">
<div class="date"> days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ best_comment.comment }}
</p>
</div>
</div>
{% endif %} <div class="ui divider"></div> {% 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"> days ago</div>
</div>
<p class="text" style="font-family: 'Raleway', sans-serif;">
{{ comment.comment }}
</p>
</div>
</div>
{% endfor %} </div>

    

  

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/585724.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存