让我们做以下假设
- 模板名称:MyTemplate.html
- 网址定义:url(r'^/some/url/defn/$', 'some_app.controller.handler'),
- 名为 InputForm 的表单
我的模板.html
<form method='POST' action='.'> <!-- posts to self -->
{% csrf_token %}
<table>
{% form.as_table %}
</table>
<input type="submit" value="Submit" />
</form>
表格.py
class InputForm(forms.Form):
# ... other fields
time = forms.CharField(max_length=25)
def clean(self):
"""
your form validations
"""
cleaned_data = super(InputForm, self).clean()
time = cleaned_data.get('time')
# validate your times format here
if not time_valid(time): # you need to do your own validation here
self._errors['time'] = self.error_class(['time is invalid!'])
return cleaned_data # always return the cleaned data! always :)
控制器.py
from some_app.forms import InputForm
from some_app.models import Task
@csrf_protect
def handler(request):
template_file = 'MyTemplate.html'
template_info = {
'form': InputForm()
}
if request.method = 'POST':
form = InputForm(request.POST)
template_info['form'] = form
if form.is_valid():
# retrieve your related model here
task = Task.objects.filter(field='lookupvalue')
# this makes huge assumptions,
# namely that your form validations ensure that the form data
# is in the proper format to go into the database
task.phase(form.cleaned_data.get('time'))
# save your model data
task.save()
else:
# spit out any warnings here?
pass
return render(request, template_File, template_info)
现在将您的浏览器指向您http://your_dev_server:[port]/some/url/defn/
将看到一个模板,该模板在完成后将处理一些表单验证(并以错误响应),如果成功则phase()
针对任务对象调用您的方法!