M_J
M_J

Reputation: 316

Passing values into django forms

I have googled around trying to figure out and understand how this works, yet I still haven't grasped this quite right. What I want to do is pass a value into a form to then use for a query. I have a session variable called menu_term, which determines the choices in the form.

from views.py

def manage_groups(request):
    form = CourseGroupForm(request,current_term=request.session.get('menu_term'))
return render_to_response("accounts/group_management.html", {'form':form}, context_instance=RequestContext(request))   

from forms.py

 class CourseGroupForm(ModelForm):
 def __init__(self, current_term, *args, **kwargs):
    super(CourseGroupForm, self).__init__(*args, **kwargs)
    courseslist = Course.objects.filter(term=current_term, num_in=settings.LAB_COURSES).order_by('description').distinct();
    print(courseslist)
    self.fields['courses'].queryset = forms.ChoiceField(label='Select Course', choices=courseslist)

class Meta:
    model = CourseGroup
    fields = ['name','courses'];

The error I am getting is:

 __init__() got multiple values for keyword argument 'current_term'

For the benefit of anyone else coming across this, what are the proper ways of defining a form that takes a value passed in from outside?

Thanks, Good Day MJ

Upvotes: 1

Views: 819

Answers (2)

dm03514
dm03514

Reputation: 55962

Its important to pop the kwarg you instantiate your form with before calling the forms super __init__

class CourseGroupForm(ModelForm):
 def __init__(self, current_term, *args, **kwargs):
    current_term = kwargs.pop('current_term')
    super(CourseGroupForm, self).__init__(*args, **kwargs)

The above assumes current_term is always present.

as @vishen pointed out, check your arguments, you are initializing your form with request as the value for current_term

Upvotes: 5

vishen
vishen

Reputation: 469

The error is happening because in your model form init decleration

 class CourseGroupForm(ModelForm):
     def __init__(self, current_term, *args, **kwargs)

current_term is the first argument that the form is expecting to find, but because you are passing through the request object first and then the current_term after that, your effiectely passing the following

form = CourseGroupForm(current_term=request,current_term=request.session.get('menu_term'))

Hence the multiple values for keyword argument 'current_term' error message.

Upvotes: 2

Related Questions