A
A
Alexander Vinogradov2019-01-03 14:21:46
Django
Alexander Vinogradov, 2019-01-03 14:21:46

How to get additional arguments in the view?

The documentation talks about passing extra arguments from the url in the view.
Example:

urlpatterns = [
    url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),]

But how in the view class to get this foo argument?
For example here:
class BasicCaseView(generic.ListView):

    queryset = models.StandardCases.objects.all().filter(type_case='case')
    template_name = 'core/basic_modules.html'
    context_object_name = 'bases'

In my example, I am passing an additional argument filtr and I want to get it in my BasicCaseView class
path('basic/case/', views.BasicCaseView.as_view(), {'filtr':'case'}, name='basiccase'),

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-01-03
@sergey-gornostaev

In any of the methods of the view class, you can access the named argument with self.kwargsFor example, like this:

class BasicCaseView(generic.ListView):
    template_name = 'core/basic_modules.html'
    context_object_name = 'bases'

    def get_queryset(self):
        return models.StandardCases.objects.filter(type_case=self.kwargs['filtr'])

Relevant section of the documentation.

Y
Yura Khlyan, 2019-01-03
@MAGistr_MTM

class BasicCaseView(generic.ListView):

    def __init__(self):
        super(BasicCaseView).__init__()
        self.filtr1 = self.kwargs['filtr']

    
    def foo(self):
        self.filtr1 # он здесь будет доступен

P.S. you must first learn (at least a little) a programming language, and only then climb into its frameworks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question