6

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())

2 Answers 2

11

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/')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing me in the right direction. I am using django-registration and have added the account creation logic to the activate function and its working properly.
it's bad practice to use GET method to create resources in backend. should use POST/PUT/PATCH
-1

I don't believe a view needs to do anything explicit with a form if it does not need one.

You can instantiate a Reviewer object. It's just a python object.

class ReviewerCreateView(CreateView):
    model = Reviewer

    self.object.user = self.request.user
    self.object.role = 2
    self.object.save()
    return HttpResponseRedirect(self.get_success_url())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.