Data transfer for Jinja2 from Updateviev

Question:

I have such a template on every html page into which I want to transfer data from my url processors:

{% block title %} {{ title }} {% endblock %}
{% block username %} <b>{{username}}</b> {% endblock %}

When using regular def functions, I pass them like this:

data_ = {
    'form': form,
    'data': data,
    'username': user_name,
    'title': 'Add campaign page'
}
return render(request, 'dashboard/add_campaign.html', data_)

But when I use a class based on UpdateView:

class CampaignEditor(UpdateView):
    model = Campaigns
    template_name = 'dashboard/add_campaign.html'
    form_class = CampaignsForm

There is a slightly different data structure, could you tell me how to pass the required date through the class?

Asked By: juniorDev

||

Answers:

You override get_context_data:

class CampaignEditor(UpdateView):
    model = Campaigns
    template_name = 'dashboard/add_campaign.html'
    form_class = CampaignsForm

    def get_context_data(self, *args, **kwargs):
        return super().get_context_data(
            *args,
            **kwargs,
            data='some_data',
            title='Add campagin page',
            username=self.request.user
        )

This builds the dictionary that is passed to the template. The UpdateView will already populate this for example with the form.

Answered By: Willem Van Onsem
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.