发布文章
在article/models.py中创建数据模型
from django.utils import timezone
from django.urls import reverse
from django.template.defaultfilters import slugify
class ArticlePost(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=500)
column = models.ForeignKey(ArticleColumn, related_name="article_column", on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(default=timezone.now())
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ("title",)
index_together = (("id", "slug"),) #对id,slug字段建立索引
def __str__(self):
return self.title
def save(self, *args, **kargs): #重写save
self.slug = slugify(self.title) #实现slug
super(ArticlePost, self).save(*args, **kargs)
def get_absolute_url(self):
return reverse("article:article_detail", args=[self.id, self.slug]) #获取某篇文章的url
在article/forms.py中创建表单
class ArticlePostForm(forms.ModelForm):
class Meta:
model = ArticlePost
fields = ("title", "body")
在article/views.py中创建视图函数
@login_required(login_url="/account/login")
@csrf_exempt
def article_post(request):
if request.method == "POST":
article_post_form = ArticlePostForm(data=request.POST)
if article_post_form.is_valid():
cd = article_post_form.cleaned_data
try:
new_article = article_post_form.save(commit=False)
new_article.author = request.user
new_article.column = request.user.article_column.get(id=request.POST["column_id"])
new_article.save()
return HttpResponse("1")
except:
return HttpResponse("2")
else:
return HttpResponse("3")
else:
article_post_form = ArticlePostForm()
article_columns = request.user.article_column.all() #通过创建ArticleColumn建立的外键参数related_name='article_column'查找对应数据
return render(request, "article/article_post.html", {"article_post_form": article_post_form, "article_columns": article_columns})
在article/urls.py中设置url
path("article-post/", views.article_post, name="article_post"),
在templates/article/article_post.html文件中写前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form class="form-horizontal" action="#" method="post">
{% csrf_token %}
<span>标题:</span>
{{article_post_form.title}}<br>
<div class ='row' style="margin-top:10px;">
<div class='col-md-2 text-right'><span>栏目:</span></div>
<div class="col-md-10 text-left">
<select id="which_column">
{% for column in article_columns %}
<option value="{{column.id}}">{{column.column}}</option>
{% endfor %}
</select>
</div>
</div>
<span>内容:</span>
<div class="col-md-10 text-left">
{{article_post_form.body}}
</div>
<input type="button" class="btn btn-primary btn-lg" value="发布" onclick="publish_article()">
</form>
<p><a href="{% url 'article:article_column' %}">栏目管理</a></p>
{% load staticfiles %}
<script type="text/javascript" src="{% static '/js/jquery.js' %}"></script>
<script type="text/javascript" src="{% static '/js/layer/layer.js' %}"></script>
<script>
function publish_article() {
var title = $("#id_title").val();
var column_id = $("#which_column").val();
var body = $("#id_body").val();
$.ajax({
url:"{% url 'article:article_post' %}",
type:"POST",
data:{"title":title, "body":body, "column_id":column_id},
success:function (e) {
if(e=="1"){
layer.msg("successful");
}else if(e=="2"){
layer.msg("sorry")
}else{
layer.msg("项目名称必须写")
}
},
});
}
</script>
</body>
</html>
在templates/article/header.html中添加一个连接
<p><a href="{% url 'article:article_post' %}">发布文章</a></p>
新增文章显示
在article/views.py中创建视图函数
@login_required(login_url="/account/login")
def article_list(request):
articles = ArticlePost.objects.filter(author=request.user)
return render(request, "article/article_list.html", {"articles": articles})
在templates/article/article_list.html中编写简单的前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% load staticfiles %}
<table class="table table-hover">
<tr>
<td>序号</td>
<td>标题</td>
<td>栏目</td>
<td>操作</td>
</tr>
{% for article in articles %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{article.title}}</td>
<td>{{article.column.column}}</td>
<td>
--
</td>
</tr>
{% empty %}
<p>没有设置栏目</p>
{% endfor %}
</table>
</body>
</html>
article/urls.py中新增路由
path("article-list/", views.article_list, name="article_list"),
在templates/article/header.html中增加一个连接
<p><a href="{% url 'article:article_list' %}">文章列表</a></p>
查看文章内容
将显示文章名称的部分修改成链接templates/article/article_list.html
<td><a href="{{article.get_absolute_url}}">{{article.title}}</a></td>
在article/views.py中增加视图函数
@login_required(login_url="/account/login")
def article_detail(request, id, slug):
article = get_object_or_404(ArticlePost, id=id, slug=slug)
return render(request, "article/article_detail.html", {"article": article})
在article/urls.py中增加新的路由
path("article-detail/(?P<id>\d+)/(?P<slug>[-\w]+)/", views.article_detail, name="article_detail"),
对文章添加删除,再templates/article/article_list.html文件中添加
<td>
<a name="edit" href="javascript:" onclick="edit_column(this,{{article.id}})"><span class="glyphicon glyphicon-pencil"></span></a>
<a name="delete" href="javascript:" onclick="del_article(this,{{article.id}})"><span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span></a>
</td>
......
<script>
function del_article(the, article_id) {
var article_name=$(the).parents("tr").children("td").eq(1).text();
layer.open({
type:1,
skin:"layui-layer-rim",
area:["400px","200px"],
title:"删除文章",
content: '<div class="text-center" style="margin-top:20px"><p>是否确定删除《'+ article_name +'》</p></div>',
btn:["确定","取消"],
yes:function(){
$.ajax({
url:"{% url 'article:del_article' %}",
type:"POST",
data:{"article_id":article_id},
success:function (e) {
if(e=="1"){
parent.location.reload();
layer.msg("has been deleted");
}else{
layer.msg("删除失败")
}
},
});
},
});
}
</script>
article/views.py添加视图函数
@login_required(login_url='/account/login')
@require_POST
@csrf_exempt
def del_article(request):
article_id = request.POST["article_id"]
try:
article = ArticlePost.objects.get(id=article_id)
article.delete()
return HttpResponse("1")
except:
return HttpResponse("2")
article/urls.py添加
path("del-article", views.del_article, name="del_article"),
是不是发现我的界面有格式了,因为我添加bootstarp
引入过程在这里简单说一下
html文件中要加入配置文件,配置文件要在static静态文件中
<link rel="stylesheet" href="{% static '/js/bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">