How to pass variables between class based Views in Django?

I've created url-shorter service using Django. For creating short link i use CreateView:

class LinkCreate(CreateView):
    form_class = CreateLink
    template_name = "index.html"
    success_url = reverse_lazy('users_links')

    def form_valid(self, form):
        if self.request.user.is_authenticated:
            form.instance.creator = self.request.user

        self.link_short = generate_short_link()
        
        self.request.session["new_link"] = self.link_short

        form.instance.link_short = self.link_short
        return super().form_valid(form)

    # Showing last 5 shorted links on the page
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['object_list'] = URL.objects.all().order_by('-id')[:5]
        return context

After creating new link user is redirected to page "users_links" where he should see new shotred link. For this reason in template i use something like that:

{% if request.session.new_link %}
    <div>
        Your new link: request.session.new_link
    </div>
{% endif %}

The problem is user see that 'div' all the time till the end of session. I think this is wrong decision to using session variables in this case, but i don't know how to pass variable between views in another way.

I'm newbie in Django, can you please give me advice how to do it in the right way?

{% for url in object_list %}
<div>
Your new link: {{url}}
</div>
{% endfor %}

Maybe do the introduction of Django first before jumping in CBV, showing variable should be pretty easy and CBV are a bit abstracts so it is better to understand how they work.

object_list is not a good variable name either, you should call it "links" because you return a list of links.

Back to Top