http://localhost:8000/myapp/author_update/1/
点击提交后,窗口显示Thanks!,同时将更新内容存入数据库。当使用自带测试服务器时,再次访问http://localhost:8000/myapp/author_update/1/ 很有可能得不到更新后结果。
一、目录结构:
mysite/
manage.py
myapp/
__init__.py
urls.py
models.py
tests.py
views.py
templates/
myapp/
thanks.html
author_update_form.html
mysite/
__init__.py
settings.py
urls.py
wsgi.py
# mysite/mysite/urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^myapp/', include('myapp.urls')),
)
# mysite/myapp/urls.py
from django.conf.urls import patterns, url
from .views import AuthorUpdate, ThanksView
urlpatterns = patterns('',
url(r'^author_update/(?P<pk>\w+)/$', AuthorUpdate.as_view()),
url(r'^thanks/', ThanksView.as_view()),
)
# mysite/myapp/views.py
from django.views.generic import TemplateView
from django.views.generic.edit import UpdateView
class ThanksView(TemplateView):
template_name = 'myapp/thanks.html'
class AuthorUpdate(UpdateView):
model = Author
template_name_suffix = '_update_form'
success_url = '/myapp/thanks/'
# mysite/myapp/models.py
from django.db import models
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __unicode__(self):
return '%s %s' % (self.first_name, self.last_name)
# mysite/myapp/templates/myapp/author_update_form.html
<html>
<head><title>Author Update</title></head>
<body>
<form method="post">
{% csrf_token %}
<table>
<tr><th>First Name</th><td>{{ form.first_name }}</td></tr>
<tr><th>Last Name</th><td>{{ form.last_name }}</td></tr>
<tr><td colspan="2"><input type="submit" /></td></tr>
</form>
</body>
</html>
# mysite/myapp/templates/myapp/thanks.html
<html>
<head><title>Thanks!</title></head>
<body>
Thanks!
</body>
</html>