1

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

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

You can also call 'del' on the kwarg: "del kwargs['current_term']" to remove it.
Also, point out that this line "self.fields['courses'].queryset = forms.ChoiceField(label='Select Course', choices=courseslist)" is wrong. He's assigning a field where a queryset should be given
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.