html 基于类的视图中的两种形式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 基于类的视图中的两种形式相关的知识,希望对你有一定的参考价值。
from django.views.generic import UpdateView
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse_lazy
from app.models import Model
from app.forms import Form1, Form2
class MyView(UpdateView):
template_name = 'template.html'
form_class = Form1
second_form_class = Form2
success_url = reverse_lazy('success')
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
if 'form' not in context:
context['form'] = self.form_class(initial={'some_field': context['model'].some_field})
if 'form2' not in context:
context['form2'] = self.second_form_class(initial={'another_field': context['model'].another_field})
return context
def get_object(self):
return get_object_or_404(Model, pk=self.request.session['someval'])
def form_invalid(self, **kwargs):
return self.render_to_response(self.get_context_data(**kwargs))
def post(self, request, *args, **kwargs):
# get the user instance
self.object = self.get_object()
# determine which form is being submitted
# uses the name of the form's submit button
if 'form' in request.POST:
# get the primary form
form_class = self.get_form_class()
form_name = 'form'
else:
# get the secondary form
form_class = self.second_form_class
form_name = 'form2'
# get the form
form = self.get_form(form_class)
# validate
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(**{form_name: form})
<form action="{% url 'myview' %}" method="post" enctype="multipart/form-data">
...
<input type="submit" name="form" value="Submit" />
</form>
<form action="{% url 'myview' %}" method="post" enctype="multipart/form-data">
...
<input type="submit" name="form2" value="Submit" />
</form>
以上是关于html 基于类的视图中的两种形式的主要内容,如果未能解决你的问题,请参考以下文章