[英]How do I use **kwargs in Python 3 class __init__ function?
[英]How do I pass **kwargs when instantiating an object and access it in the class's __init__() method
在這里,我想在實例化我的 PlayerForm 對象時傳遞一個**kwargs
字典,並在調用__init__()
方法時能夠訪問它。 這是我在下面所做的,但它不起作用。
這是在我的 views.py 文件中的某處:
context = {'player_form': PlayerForm(kwargs={'user': request.user})}
這是在我的 forms.py 文件中
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)
您可以使用 ** 運算符來使用 kwargs。 嘗試使用以下代碼:
context = {'player_form': PlayerForm(**{'user': request.user})}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.