-1

Here I'd like to pass a **kwargs dictionary when instantiating my PlayerForm objects and be able to access it when calling __init__() method. This is what I've done below but it's not working.

This is somewhere in my views.py file:

context = {'player_form': PlayerForm(kwargs={'user': request.user})}

This is in my forms.py file

from .models import Game, Player

class PlayerForm(forms.ModelForm):

class Meta:
    model = Player
    fields = ['game', 'username']

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    if kwargs.get('user'):
        self.fields['game'].queryset = Game.objects.exclude(player__user=user)
cy23
  • 354
  • 1
  • 3
  • 12
  • 1
    What is not working with it? Are you getting an error? (post the error here). Are you getting an unexpected output? (Post the expected output and what you are getting here) – user1558604 Jul 18 '20 at 02:09
  • 2
    I've never seen someone actually use kwargs as a parameter when instantiating the object. Try `context = {'player_form': PlayerForm(user = request.user)}` – user1558604 Jul 18 '20 at 02:11
  • 1
    A function parameter like `**` means "collect all remaining keyword arguments as a dictionary and store them in " – Iain Shelvington Jul 18 '20 at 02:13
  • Does this answer your question? [Normal arguments vs. keyword arguments](https://stackoverflow.com/questions/1419046/normal-arguments-vs-keyword-arguments) – Josh J Jul 18 '20 at 02:14
  • @user1558604 the solution worked for me. :) – cy23 Jul 18 '20 at 02:16

1 Answers1

0

You can use kwargs using ** operator. Try using below code:

context = {'player_form': PlayerForm(**{'user': request.user})}
Astik Gabani
  • 599
  • 1
  • 4
  • 11
  • 2
    This is unnecessary and less readable than passing keyword arguments directly – Josh J Jul 18 '20 at 02:16
  • 1
    You r right, but there might be the case where all the args would be in dictionary format. Ane question author wants it to work like this. – Astik Gabani Jul 18 '20 at 02:18