Olivier Pons
Olivier Pons

Reputation: 15778

Python beginner with class variables

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?

Upvotes: 2

Views: 61

Answers (2)

Antoine Pinsard
Antoine Pinsard

Reputation: 34942

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.

Upvotes: 0

Dan Breen
Dan Breen

Reputation: 12924

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.

Upvotes: 1

Related Questions