Skip to content

Instantly share code, notes, and snippets.

@chriskief

chriskief/views.py

Created Oct 24, 2013
Embed
What would you like to do?
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})
@mikelopez

This comment has been minimized.

Copy link

@mikelopez mikelopez commented Jun 30, 2014

What if you wanted to have multiple forms where they simply render on an HTML form and they all submit to one URL ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment