Ali
Ali

Reputation: 535

render_to_response() - KeyError: 'object'

I'm working on Django. I'm getting the error below. I didn't find the solution despite the much increased. I'd appreciate it if you could help.

/core/views.py

class CreateVote(LoginRequiredMixin, CreateView):
form_class = VoteForm

def get_initial(self):
    initial = super().get_initial()
    initial['user'] = self.request.user.id
    initial['movie'] = self.kwargs[
        'movie_id'
    ]
    return initial

def get_success_url(self):
    moive_id = self.object.moive.id
    return reverse(
        'core:MovieDetail',
        kwargs = {
            'pk':moive_id
        }
         )    
def render_to_response(self, context, **response_kwargs):
    movie_id = context['object']
    movie_detail_url = reverse(
        'core:MovieDetail',
        kwargs = {'pk':movie_id }
    )

    return redirect(
        to=movie_detail_url) 

I could not find movie.id from render_to_response returns context dic.

error page

Traceback screen- print

Upvotes: 1

Views: 331

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

A CreateView basically is used twice in the creation process:

  1. once to construct the form to create the object, in which case, there is no created object yet; and
  2. once for the POST that will construct the object.

There are two cases where render_to_response is called:

  1. when we perform a GET, and thus create the the form, at which point there is no object, (self.object = None, so that means it is not added to the context data); and
  2. when we perform a POST, and the form turns out to be invalid, in that case the form is typically rerendered with the error.

You can use self.object to access the object that is creates, but as said before, it is rather non-sensical here to access it, since render_to_response, is used to render a form in case it was not filled in yet, or filled in with errors.

Typically one specifies the template that renders the form, for example like:

class CreateVote(LoginRequiredMixin, CreateView):
    form_class = VoteForm
    template_name = 'app/some_template.html'

    def get_initial(self):
        initial = super().get_initial()
        initial['user'] = self.request.user.id
        initial['movie'] = self.kwargs['movie_id']
        return initial

    def get_success_url(self):
        movie_id = self.object.moive.id
        return reverse('core:MovieDetail', kwargs = {'pk': movie_id })

    # no render_to_response override

Upvotes: 1

Related Questions