Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django CreateView without Form to Create Object

I am using classed based views with django 1.3 and am trying to figure out how to create an object without using the form. I do not need any user input to create the object but I am still getting an error message that the template is missing. Below is my current view where I have tried to subclass the form_valid method but its not working. Any help would be appreciated.

class ReviewerCreateView(CreateView):
    model = Reviewer

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.role = 2
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())
like image 659
thesteve Avatar asked Jun 03 '11 02:06

thesteve


1 Answers

A CreateView is a specialized view whose purpose is to display a form on GET and validate the form data and create a new object based on the form data on POST.

Since you don't need to display a form and process the form data, a CreateView is not the tool for your job.

You either need a plain old function-based view, or, if you prefer to use a class-based view, derive from View and override get() or post(). For example, adapting your sample code:

class ReviewerCreator(View):
    def get(self, request, *args, **kwargs):
         Reviewer(user=request.user, role=2).save()
         return HttpResponseRedirect('/your_success_url/')
like image 52
tawmas Avatar answered Sep 27 '22 20:09

tawmas