I'm having trouble wrapping my head around how to use generic class based 
views properly when it comes to creating objects associated with already 
created objects.

The concept here is adding File objects to a Case object.

The url pattern would be something like:

url(r'^case/(?P<pk>\d+)/add/$', AddFileToCase.as_view(), {}, 'file-add')


So going to case/1/add would prompt the user with a form to add a file to 
case with pk = 1.

The following code below is doing what I want but I'm not sure it's the 
best way to handle it. I feel the documentation to be very lacking in this 
area.

class AddFileToCase(CreateView):
    model = File
    form_class = FileForm #all of the file fields exposed except for the 
foreign key relationship field to Case

    def dispatch(self, request, *args, **kwargs):
        self.case = Case.objects.get(pk=self.kwargs['pk'])
        return super(AddFileToCase, self).dispatch(request, *args, **kwargs)


    def form_valid(self, form):
        form.instance.case= self.case
        return super(AddFileToCase, self).form_valid(form)


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to