[Fixed]-'CheckoutView' object has no attribute 'object'

43πŸ‘

βœ…

You need to assign object to your view using .get_object() in the post method of your view.

This is because Django’s get_context_data() function uses the object to pass it into the context. In case of errors in POST request, this function will be called and it will look for self.object which you did not assign, thereby leading to the error.

class CheckoutView(FormMixin , DetailView):
    model = Cart
    template_name = "carts/checkout_view.html"
    form_class = GuestCheckoutForm

    ...

    def post(self , request , *args , **kwargs):
        self.object = self.get_object() # assign the object to the view
        form = self.get_form()
        if form.is_valid():
            email = form.cleaned_data.get("email")
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Also, it would be better to use UpdateView here instead of DetailView.

πŸ‘€Rahul Gupta

2πŸ‘

For me the solution was to initialize self.object to [] (empty list) in get_context_data.

0πŸ‘

Remember these are classes and self is like soul of classes.

def get(self, request, id):
        user_g = **self**.get_object(id)
πŸ‘€Lord-shiv

Leave a comment