pavan kumar
pavan kumar

Reputation: 93

where this "username" came from, self.kwars.get('username')?

In url parameters I didn't pass username but when I used self.kwars.get('username) where did username comes from

In urls.py

path('', views.PostList.as_view(), name='all')

In views.py

class PostList(SelectRelatedMixin, generic.ListView):
model = models.Post
select_related = ('user', 'group')
template_name = 'posts/post_list.html'

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    print(self.kwargs.get('username'))
    context['user_groups'] = models.Group.objects.filter(members__in=self.kwargs.get('username',''))

    return context

I tried to print self.kwargs.get('username') but it is printing "None"

but this line context['user_groups'] = models.Group.objects.filter(members__in=self.kwargs.get('username','')) is returning Group data

Upvotes: 0

Views: 829

Answers (1)

Ersain
Ersain

Reputation: 1520

self.kwargs is a python dictionary, when you execute self.kwargs.get(<key>) it returns a value from the dictionary if the key exists and None otherwise. Since your self.kwargs does not contain a username entry, it returns None and does not raise an error

E.g.

foo = dict()
print(foo.get('bar'))  # Outputs None

Upvotes: 3

Related Questions