我想制作一个DetailView页面,例如:
class TaskDetailView(DetailView):
model = Task
template_name = 'todo/task_detail.html'
并将表单放置在此页面中,以便用户可以添加此任务。
如果为此表单创建新页面,则非常简单:
表格
class TaskForm(ModelForm):
class Meta:
model = task
fields = __all__
views.py
def TaskForm_view(request, pk):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid(): # All validation rules pass
task.save()
return HttpResponseRedirect('/admin/') # Redirect after POST
else:
form = TaskForm() # An unbound form
return render(request, 'todo/add_task.html', {
'form': form,
})
urls.py:
url(r'^(?P<pk>\d+)/add/', 'todo.views.TaskForm_view', name='add')
但是如何使用表单创建一个DetailView页面呢?我找不到一个例子,请帮助!
最佳答案
您可以将表单添加到上下文变量中,因此可以通过以下模板从模板访问表单:
class TaskDetailView(DetailView):
model = Task
template_name = 'todo/task_detail.html'
def get_context_data(self, **kwargs):
context = super(TaskDetailView, self).get_context_data(**kwargs)
context['form'] = TaskForm()
return context