点击提交后,窗口显示thanks,同时将输入内容保存至数据库。
一、目录结构:
mysite/
manage.py
myapp/
__init__.py
urls.py
models.py
tests.py
views.py
templates/
myapp/
thanks.html
author_create_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 AuthorCreate, ThanksView
urlpatterns = patterns('',
url(r'^author_create/', AuthorCreate.as_view()),
url(r'^thanks/', ThanksView.as_view()),
)
# mysite/myapp/views.py
from django.views.generic import TemplateView
from django.views.generic.edit import CreateView
class ThanksView(TemplateView):
template_name = 'myapp/thanks.html'
class AuthorCreate(CreateView):
model = Author
template_name_suffix = '_create_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_create_form.html
<html>
<head><title>Author Create</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>
>>> from myapp.models import Author
>>> Author.objects.all()[4]
<Author: Steve Jobs>