You can subclass the general view of edit.CreateView , set the class / course in the dispatch() method and save it by overriding the form_valid() method:
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.views.generic.edit import CreateView class CourseEntryCreateView(CreateView): form_class = CourseEntryForm model = CourseEntry def dispatch(self, *args, **kwargs): self.course = get_object_or_404(Class, pk=kwargs['class_id']) return super(CourseEntryCreateView, self).dispatch(*args, **kwargs) def form_valid(self, form): self.object = form.save(commit=False) self.object.course = self.course self.object.save() return HttpResponseRedirect(self.get_success_url())
If you do not configure CourseEntryForm ModelForm , you can leave the form_class property.
Unfortunately, it is not possible to call super() in the form_valid() method - due to the way it was written, this means that the object will be saved again.
If you need an instance of the class (course?) In the context of the template, you can add it to the get_context_data() method:
def get_context_data(self, *args, **kwargs): context_data = super(CourseEntryCreateView, self).get_context_data( *args, **kwargs) context_data.update({'course': self.course}) return context_data
Matt austin
source share