Home > Software design >  Data transfer for Jinja2 from Updateviev
Data transfer for Jinja2 from Updateviev

Time:11-21

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?

CodePudding user response:

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.

  • Related