user3084860
user3084860

Reputation: 461

Django Form Init Key Error With Kwargs

I'm trying to override the init method on this form I have. It looks like so:

def __init__(self, *args, **kwargs):
    fr = None
    if kwargs.get('friend', False):
        fr = Friend.objects.get(pk=kwargs.get('friend'))
    super(CreateFriendForm, self).__init__(*args, **kwargs)

    self.fields["{}_house".format(fr.name)] = forms.ModelChoiceField(queryset=Houses.objects.all(), required=False)

So, I want to grab the friend kwargs and use it as you see above. Depending on what friend is passed, I'll add a field. In my tests, I pass the following data:

    data = {
        "user": self.user.pk,
        "friend": self.friend.pk,
        "language": 'en'
    }
    friend = self.form(data)
    # Validity
    self.assertTrue(friend.is_valid())
    friend.save()

However, I get an error saying that there is a key error at:

if kwargs.get('friend', False):

I'm passing the necessary data (friend, user, etc), but it doesn't seem to be in the kwargs. What's the issue here? Thanks.

Upvotes: 1

Views: 1096

Answers (1)

user3084860
user3084860

Reputation: 461

Issue was that I was passing the data into the form as an arg instead of as a kwarg. Changing:

friend = self.form(data)

to:

friend = self.form(data=data)

Fixed the main problem that I was having.

Upvotes: 1

Related Questions