Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created January 14, 2013 15:31
Show Gist options
  • Select an option

  • Save bmispelon/4530805 to your computer and use it in GitHub Desktop.

Select an option

Save bmispelon/4530805 to your computer and use it in GitHub Desktop.
A form/view combo to create linked objects
# models.py
from django.db import models
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo)
# forms.py
from django import forms
from example.models import Bar
class BarForm(forms.ModelForm):
class Meta:
model = Bar
exclude = ['foo']
def __init__(self, *args, **kwargs):
self.foo = kwargs.pop('foo')
super(BarForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
bar = super(BarForm, self).save(commit=False)
bar.foo = self.foo
if commit:
bar.save()
return bar
#views.py
from django.views.generic import CreateView
from django.shortcuts import get_object_or_404
from example.models import Foo, Bar
from example.forms import BarForm
class BarCreateView(CreateView):
model = Bar
form_class = BarForm
def dispatch(self, request, *args, **kwargs):
self.foo = get_object_or_404(Foo, pk=kwargs['foo_pk'])
return super(BarCreateView, self).dispatch(request, *args, **kwargs)
def get_form_kwargs(self):
kwargs = super(BarCreateView, self).get_form_kwargs()
kwargs['foo'] = self.foo
return kwargs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment