Mihai Zamfir
Mihai Zamfir

Reputation: 2166

Create View - access to success_url from templates

say I have:

class MyCreate(CreateView):
    template_name = 'template.html'
    success_url = reverse_lazy('blabla')
    form_class = MyForm

And suppose in my template I want to add a back button. The back will lead me to the same page as success_url. My solution was to override get_context_data in MyCreate class and add {'back': self.get_success_url()} to the context.

The implications is that I have more CreateViews and I had to create a ContextMixin for this back button. Is there any other easier solution? something like accessing success_url directly in my template?

Thanks

Upvotes: 2

Views: 1158

Answers (2)

andilabs
andilabs

Reputation: 23282

In my case using Django 1.10.3 the way to get it working was like this:

view:

from django.urls.base import reverse_lazy

class FooCreateView(CreateView):
    success_url = reverse_lazy('name-of-some-view')

template:

{{ view.success_url }}

The try of using {{ view.get_success_url }} was leading to:

AttributeError 'NoneType' object has no attribute '__dict__'

Upvotes: 1

stalk
stalk

Reputation: 12054

As we can see in django (1.7) implementation of ContextMixin, we must have access to view instance from our templates:

def get_context_data(self, **kwargs):
    if 'view' not in kwargs:
        kwargs['view'] = self
    return kwargs

So you can access to success_url in templates:

{{ view.get_success_url }}

Upvotes: 3

Related Questions