1

I am trying to initialize a Django form with a parameter from a view. However when i try to use the kwargs in the form's init, i get that it's always empty. Why could it be? Am i missing something?

My view (filename: “FirstView.py”):

def create_userStory(request, proyect_id):

if request.method=='POST':
    auxForm = UserStoryForm(request.POST, proyect_id=proyect_id)

My form (filename: “forms.py”):

class UserStoryForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    proyectId = kwargs.pop('proyect_id', None)
    super(UserStoryForm, self).__init__(*args, **kwargs)
    team = Team.objects.get(proyect_id=proyectId)

I tried debugging/printing the kwargs in my form, but i always get {}, meaning that the parameter from the view did not pass.

Previously i tryied to follow these existing questions:

django form: Passing parameter from view.py to forms gives out error

Django Forms: pass parameter to form

Django formset - empty kwargs

Community
  • 1
  • 1
sdo310
  • 17
  • 1
  • 5

2 Answers2

1

I had the same problem. After one hour of searching (...), I found that in my call to __init__ :

myModelForm(request.POST, namedargument=val)

val was in fact None when I thought that it contained a value.

Then, for __init__: if namedargument=None ==> namedargument alone. And the kwargs becomes args !

That's why the kwargs was empty.

So, check your value you're passing, it's probably None by mistake.

(I know, it's a 2 years answer but I would have loved to find this one hour ago...)

ThePhi
  • 2,373
  • 3
  • 28
  • 38
0

The *args and **kwargs in the signature are use to catch arguments, that have not been taken by other defined argument positions. All untaken unnamed arguments will be placed a list args and all named arguments in a dictionary kwargs. You can change the names if you like.

An example:

def function_1(a, b, *args, **kwargs):

A call like

function_1(1, 2, 3, 4, c=5, d=6)

will result in the following variables available inside function_1:

a = 1
b = 2
args = (3, 4)
kwargs = {'c': 5, 'd': 6}

So applied on your question that means that as long you are don't have any named arguments, you will have an empty kwargs.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
  • he's got named arguments: proyect_id: ` auxForm = UserStoryForm(request.POST, proyect_id=proyect_id)` . So I don't think the problem was from here. – ThePhi Sep 01 '17 at 20:46