#首页--渲染数据库内容
def index(request):
article=models.Article.objects.all()
return render(request,'index.html',{'articles':article})
#在index.html配置超链接
template中可以用{%url 'app_name:url_name' param %} app_name:应用的空间名称,url_name:链接名
其中app_name和url_name都在url中配置
再配URl
第一种方法:根urls,写在include()的第二个参数位置,namespace='blog' 这就是应用的命名空间
第二种方法:应用下则写在path()的第三个参数位置,name='article',
如果报错registered namespace就在应用.urls中加入app_name='应用名'
这两种写法的区别主要取决于是否使用include引用了另一个url配置文件
#内容页-根据id进行渲染
def articel_page(request,article_id):
article=models.Article.objects.get(pk=article_id)
return render(request,'article_page.html',{'article':article})
#配置url
from django.urls import path,re_path
from . import views
urlpatterns = [
path('', views.index),
re_path('article/(?P<article_id>[0-9]+)', views.articel_page),
]
#编写新增页面/编辑页面
def edit_page(request,article_id):
if article_id=='0':#因为文章id都是从1开始
return render(request,'edit_page.html')
article=models.Article.objects.get(pk=article_id)#如果不为0就取出article这个对象
return render(request,'edit_page.html',{'article':article})
//re_path('edit/(?P<article_id>[0-9]+)', views.edit_page,name='edit_page'),
//在新增文字的url处要添加个参数0和在修改文章的url处要填写{% url 'blog:edit_page' article.id %}
//在edit_page.html中判断是否有article对象有的话给个value值,因为要编辑所以有一种方法就是给个标签属性为隐藏然取到ID进行判断
并配置url
edit_page.html:因为是post请求所有必须加一个{% csrf_token %} from提交后的数据到enit_action视图函数
-------------
使用request.POST['参数名']获取表单数据
models.Article.objects.create(title,content)创建对象
#进行处理请求
def edit_action(request):
title=request.POST['title']
content=request.POST['content']
article_id=request.POST['article_id']
models.Article.objects.create(title=title,content=content)
if article_id=='0':
#返回到首页这种方法有点low
article=models.Article.objects.all()
return render(request,'index.html',{'articles':article})
article=models.Article.objects.get(pk=article_id)
article.title=title
article.content=content
article.save()
return render(request, 'article_page.html', {'article': article})
Django-简单的博客页面
最新推荐文章于 2022-08-05 13:47:09 发布