$ python manager startapp jlpt
jlpt1/ ├── admin.py ├── __init__.py ├── models.py ├── tests.py └── views.py 0 directories, 5 files
url(r‘^jlpt/‘, include(‘jlpt.urls‘)),
from django.conf.urls import patterns, include, url
urlpatterns = patterns(‘‘,
url(r‘^$‘, ‘jlpt.views.home‘, name=‘home‘),
)
http://yourdomain.com/jlpt时,会导向到名叫home的view.下面我们来定义home这个view.from django.shortcuts import render
from django.http import HttpResponse
from jlpt.forms import ExamInfoForm
# Create your views here.
def home(request):
if request.method == ‘POST‘:
form = ExamInfoForm(request.POST)
if form.is_valid():
exam_info = form.save()
exam_info.save()
return HttpResponse(‘Thank you‘)
else:
form = ExamInfoForm()
return render(request, ‘jlpt/index.html‘, {‘form_info‘: form})
ModelFormfrom django.forms import ModelForm
from jlpt.models import ExamInfo
class ExamInfoForm(ModelForm):
class Meta:
model = ExamInfo
fields = ‘__all__‘
from django.db import models
# Create your models here.
LEVEL_CHOICES = (
(‘N1‘, ‘N1‘),
(‘N2‘, ‘N2‘),
(‘N3‘, ‘N3‘),
(‘N4‘, ‘N4‘),
(‘N5‘, ‘N5‘),
(‘NO‘, ‘NO‘),
)
class ExamInfo(models.Model):
name = models.CharField(max_length=10)
level = models.CharField(max_length=2, choices=LEVEL_CHOICES)
<!DOCTYPE html>
</html>
<head>
<title>报名情况统计</title>
</head>
<body>
<p style="text-align:center;font-size:1.5em;">少年よ、大志を抱け!</p>
<form action="/jlpt/" method="post">
{% csrf_token %}
<fieldset>
<legend>你要参加2014年7月JLPT的哪个等级考试?</legend>
{{ form_info.as_p }}
<input type="submit" value="submit" />
</fieldset>
</form>
</body>
</html>
return render(request, ‘jlpt/index.html‘, {‘form_info‘: form})通过传递form(这个html文件中为form_info)来渲染这个页面.from django.contrib import admin
from jlpt.models import ExamInfo
# Register your models here.
class ExamInfoAdmin(admin.ModelAdmin):
list_display = [‘name‘, ‘level‘]
admin.site.register(ExamInfo, ExamInfoAdmin)
name和level两列.# Application definition
INSTALLED_APPS = (
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘your project name‘,
‘jlpt‘,
)
Django的ModelForm简单用法,布布扣,bubuko.com
原文地址:http://blog.csdn.net/feelang/article/details/25040873