Home > Net >  How to call a function in django view.py
How to call a function in django view.py

Time:01-24

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

CodePudding user response:

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
  • Related