2

I'm trying to define a variable in my view like this:

class PostMessageView(LoginRequiredMixin, generic.TemplateView):
    url_redirect = None

    def post(self, request, *args, **kwargs):
        return redirect(self.url_redirect)

I know this is not the good way, and there are build-in classes for that, but my problem is not here. My problem is about pure Python (I guess). If I make a descendant, I can do it like that, it works:

class ContactDetailView(PostMessageView):
    template_name = 'my_home/contact_detail.html'
    url_redirect = 'my_profile_contact_detail'

My problem is when I want to change url_redirect with a dynamic value, like:

class ContactDetailView(PostMessageView):
    template_name = 'my_home/contact_detail.html'

    def get_context_data(self, **kwargs):
        self.url_redirect = self.request.build_absolute_uri(self.request.path)

Then I get argument of type 'NoneType' is not iterable because, I guess, self.url_redirect doesn't overwrite url_redirect.

How to do it properly in Python?

0

2 Answers 2

1

You can use a property for this:

class ContactDetailView(PostMessageView):
    template_name = 'my_home/contact_detail.html'

    @property
    def url_redirect(self):
        return self.request.build_absolute_uri(self.request.path)

This url_redirect method essentially acts like an attribute of the class. Using the decorator version like this will make it a getter only. You can use property as a method instead, if you wanted to make a setter as well.

Sign up to request clarification or add additional context in comments.

Comments

0

The issue is that get_context_data() is not called as it should be called by your post() method.

This should work:

def post(self, request, *args, **kwargs):
    self.get_context_data()
    return redirect(self.url_redirect)

However, get_context_data() is supposed to return a dictionary of data to pass to the template, it is not supposed alter the object state.

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.