初学者render字典参数传递
自己琢磨了一下,把字典参数分别命名了,便于理解页面跳转顺序,给大家参考一下。
urls.py
urlpatterns = [ url(r'^index/', views.index), url(r'^article/(?P<article5_id>[0-9]+)$', views.article_page,name='article_page'), url(r'^edit/(?P<article4_id>[0-9]+)$', views.edit_page,name='edit_page'), url(r'^edit/action$', views.edit_action,name='edit_action'), ]
views.py
def index(request): articles=models.Article.objects.all() return render(request, 'blog/index.html',{'article1':articles}) def article_page(request,article5_id): article=models.Article.objects.get(pk=article5_id) return render(request,'blog/article_page.html',{'article2':article}) def edit_page(request,article4_id): if str(article4_id)=='0': return render(request,'blog/edit_page.html') article = models.Article.objects.get(pk=article4_id) return render(request,'blog/edit_page.html',{'article3':article}) def edit_action(request): title=request.POST.get('title','TITLE') content=request.POST.get('content','CONTENT') article1_id=request.POST.get('article7_id','0') if article1_id=='0': models.Article.objects.create(title=title,content=content) articles=models.Article.objects.all() return render(request, 'blog/index.html',{'article1':articles}) article6=models.Article.objects.get(pk=article1_id) article6.title=title article6.content=content article6.save() return render(request,'blog/article_page.html',{'article2':article6})
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1> <a href="{% url 'blog:edit_page' 0 %}">新文章</a> </h1> {% for article in article1 %} <a href="{% url 'blog:article_page' article.id %}">{{ article.title }}</a> <br/> {% endfor %} </body> </html>
article_page.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Article Page</title> </head> <body> <h1>{{ article2.title }}</h1> <br/> <h3>{{ article2.content }}</h3> <br/><br/> <a href="{% url 'blog:edit_page' article2.id%}">修改文章</a> </body> </html>
edit_page.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Page</title> </head> <body> <form action="{% url 'blog:edit_action' %}" method="post"> {% csrf_token %} {% if article3 %} <input type="hidden" name="article7_id" value="{{ article3.id }}"/> <label>文章标题 <input type="text" name="title" value="{{article3.title}}"/> </label> <br/> <label>文章内容 <input type="text" name="content" value="{{ article3.content }}"/> </label> <br/> {% else %} <input type="hidden" name="article7_id" value="0"/> <label>文章标题 <input type="text" name="title" /> </label> <br/> <label>文章内容 <input type="text" name="content" /> </label> <br/> {% endif %} <input type="submit" value="提交"> </form> </body> </html>