Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function in django view.py

I need to call the function get_context_data in my VacanciesView.
Code views.py:

def VacanciesView(request):
    navigate_results = Navigate.objects.all()
    context_vac = { 'navigate_results': navigate_results}
    get_context_data(self, **kwargs)
    return render(request, 'main/vacancies.html', context_vac)


def get_context_data(self, **kwargs):
    context = super(VacanciesView, self).get_context_data(**kwargs)
    context['vacancies'] = sorted(get_vacancies(), key=lambda item: item["published_at"][:10])
    return context

I try to do it by get_context_data(self, **kwargs), but it takes: name ‘self’ is not defined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using Function Based View (FBV), and the function you are trying to use is a method of Class Based View (CBW).

You can go one of two ways:

stay in FBV:

def VacanciesView(request):
    navigate_results = Navigate.objects.all()
    context = {'navigate_results': navigate_results, 'vacancies': sorted(get_vacancies(), key=lambda item: item["published_at"][:10])}
    return render(request, 'main/vacancies.html', context)

switch to CBV:

class VacanciesView(TemplateView):
    template_name = 'main/vacancies.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['navigate_results'] = Navigate.objects.all()
        context['vacancies'] = sorted(get_vacancies(), key=lambda item: item["published_at"][:10])
        return context
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading