python版本3.5.2 Django版本2.1.1
from django.shortcuts import render
from django.http import HttpResponse
from . import models
def index(request):
articles = models.Article.objects.all()
return render(request, "blog/index.html", {'articles':articles})
def article_page(request,article_id):
article = models.Article.objects.get(pk=article_id)
return render(request, 'blog/article_page.html', {'article':article})
def edit_page(request):
return render(request, 'blog/edit_page.html')
def edit_action(request):
title = request.POST.get('title', 'TITLE')
content = request.POST.get('content', 'CONTENT')
models.Article.objects.create(title=title,content=content)
articles = models.Article.objects.all()
return render(request, "blog/index.html", {'articles': articles})
urls.py
from.import views
from django.urls import path, include
app_name = 'blog'
urlpatterns = [
path(r'index/',views.index),
path(r'article/<int:article_id>/',views.article_page, name= 'article_page'),
path(r'edit/', views.edit_page, name='edit_page'),
path(r'edit/action', views.edit_action, name='edit_action'),
]
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 %}
<label>文章标题
<input type="text" name="title"/>
</label>
<br/>
<label>文章内容
<input type="text" name="content"/>
</label>
<br/>
<input type="submit" value"提交">
</form>
</body>
</html>