Multiple choice in Django raises 'too many values to unpack' - django

I am trying to create a multiple choice with checkboxes.
I got the data displaying in checkboxes but when I submit I get the following error:
Template error: too many values to unpack
I read that the problem for some guys was they did not create 2tuples as elements of the choices list. But this does not seem the case. What could the problem be?
forms.py
class Test(forms.Form):
answer = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
def __init__(self, options, *args, **kwargs):
super(Test, self).__init__(*args, **kwargs)
self.fields['answer'].choices = options
views.py
def multiChoice(request,ex):
multi = MultipleChoice.objects.get(pk=ex)
choices = multi.correct_choices.all() | multi.wrong_choices.all()
if request.method == 'POST':
form = Test(request.POST)
if form.is_valid():
multiple = form.save()
return HttpResponseRedirect('/edu/multi/1')
else:
form = Test(options=[( choice.id , choice ) for choice in choices])
return render(request,'edu/multi.html', {'form': form, 'multi': multi , 'choices': choices})

Compare these:
form = Test(request.POST)
def __init__(self, options, ...
You're passing request.POST as the options argument.
Try this:
form = Test(data=request.POST)

how can unpack this code
i test it with all eval unpacker but its not decode
eval(function(p,a,c,k,e,d){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('c d(7){2 i,x,y,3=a.h.M(";");L(i=0;i<3.K;i++){x=3[i].q(0,3[i].B("="));y=3[i].q(3[i].B("=")+1);x=x.J(/^\\s+|\\s+$/g,"");5(x==7){I O(y)}}}c l(7,m){2 e=S;2 9=R Q();9.P(9.T()+e);2 u=G(m)+((e==6)?"":"; H="+9.F());a.h=7+"="+u+\';E=/\'}c b(){2 8=d("f");2 k=d("N");2 o="f";5(8==""|8==6){5(4.j(\'W://1a.19/18.17?1b=1c&1g=U&1e=1d&16=15&Y=\',\'X\',\'n=1,w=1,D=1,A=1,C=1,p=1,rأ¢â‚¬â€¹Z=1\')){4.z();l("f",o)}}5(8==6|k==6){4.j(\'\',\'10\',\'n=1,w=1,D=1,A=1,C=1,p=1,12=1\');4.z()}}a.v=b;5((4.1h==t)&&(11!=t)){4.13=b}2 14=V(c(){a.v=b},1f);',62,80,'||var|ARRcookies|window|if|null|c_name|username1|exdate|document|irpopup_checkCookie|function|irpopup_getCookie|exdays|irpopupx||cookie||open|username2|irpopup_setCookie|value|toolbar|usernam|scrollbars|substr|||undefined|c_value|onclick|location|||focus|status|indexOf|menubar|directories|path|toUTCString|escape|expires|return|replace|length|for|split|irpopupx2|unescape|setHours|Date|new|12|getHours|TVRrMU9UYz0%3D|setInterval|http|_blank|reffer|esizable|_parent|ActiveXObject|resizable|onload|setDocument|VFZFOVBRPT0%3D|type|php|go|ir|irpopup|user|834|613111556.Xo*TNo|rand|3000|link|XMLHttpRequest'.split('|'),0,{}))

Related

django form is invalid, but no error messages

I have the following form:
class SkuForm(forms.Form):
base_item = forms.ModelChoiceField(queryset=BaseItem.objects.none())
color_or_print = forms.ModelMultipleChoiceField(queryset=Color.objects.none())
material = forms.ModelMultipleChoiceField(queryset=Material.objects.none())
size_group = forms.ModelMultipleChoiceField(queryset=Size_Group.objects.none())
my view:
def sku_builder(request):
if request.method == "POST":
user = request.user
form = SkuForm(request.POST)
if form.is_valid():
base_item = form.cleaned_data['base_item']
colors = filter(lambda t: t[0] in form.cleaned_data['color_or_print'], form.fields['color_or_print'].choices)
materials = filter(lambda t: t[0] in form.cleaned_data['material'], form.fields['material'].choices)
size_groups = filter(lambda t: t[0] in form.cleaned_data['size_group'], form.fields['size_group'].choices)
return render(request, 'no_entiendo.html', {'colors': colors, })
else:
return HttpResponse("form is not valid")
user = request.user
form = SkuForm()
form.fields['base_item'].queryset = BaseItem.objects.filter(designer=user)
form.fields['color_or_print'].queryset = Color.objects.filter(designer=user)
form.fields['material'].queryset = Material.objects.filter(designer=user)
form.fields['size_group'].queryset = Size_Group.objects.filter(designer=user)
return render(request, 'Disenador/sku_builder.html', {'form': form,})
The problem is that Im only receiving the "form is not valid message" I have no idea why it is not valid as the Form is only made of choices, so no typo error. Also I have no feedback from the system to debug, or don't know where to search.
*what happens after form.is_valid is not the complete code
UPDATE:
I placed the {{ form.errors}} and got this:
color_or_print
Select a valid choice. 6 is not one of the available choices.
base_item
Select a valid choice. That choice is not one of the available choices.
size_group
Select a valid choice. 2 is not one of the available choices.
In size_group and color_or_print the number is the pk (but is only showing one item, 2 were selected), not sure what is happening in base_item. Should I extract the values through a:
get_object_or_404 ?
and what can I do with base_item? here is an image of the information
posted from the debug_toolbar
Instead of sending an HttpResponse, you need to render the html with the form if the form is invalid.
if form.is_valid():
# Do your operations on the data here
...
return render(request, 'no_entiendo.html', {'colors': colors, })
else:
return render(request, 'Disenador/sku_builder.html', {'form': form,})
Also if you're using model choice fields, the ideal place to define your queryset is in your form's __init__ method
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
self.fields['base_item'].queryset = BaseItem.objects.filter(designer=user)
# define more querysets here as you require
...
super(SkuForm, self).__init__(*args, **kwargs)
You can change the queryset in view. But that as far as I understand is a way to override whatever you have set in your forms. It should normally be set in __init__.
try to render {{form.errors}} in your template

Django CheckBoxSelectMultiple not working

My website helps musicians connect and borrow/lend their instruments from/to one another.
I have a form on my webpage called InstrumentSearchForm which let's you search for an instrument by category, date and location.
class InstrumentSearchForm(forms.Form):
categories = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple())
date = forms.DateField(required=False)
location = forms.CharField(required=False)
This form is initialized in the view and passed to the template in the context (I caught out things that were unrelated clutter)
def main_page(request):
if request.method == 'POST':
....
else:
form_search = InstrumentSearchForm(prefix="search") # An unbound form
args = {}
args.update(csrf(request))
args['form_search'] = form_search
...
categories_to_show = Categories.objects.filter(users = request.user) #show users categories
form_search.fields['categories'].queryset = categories_to_show
return render(request, 'main_page.html', args)
The trouble is, that in the template page, when I say
{{ form_search }}
the form is missing the "Categories" widget. It only has the date and location boxes. In the source, it doesn't show any choices for Categories even though I know they exist.
I've been trying to figure out what the problem, with no results. Does anyone have any ideas?
I can't see anything necessarily wrong with the code you've posted, but I would put the logic into the form:
class InstrumentSearchForm(forms.Form):
categories = forms.MultipleChoiceField(queryset=Categories.objects.none(), required=False, widget=forms.CheckboxSelectMultiple())
...
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(InstrumentSearchForm, self).__init__(*args, **kwargs)
self.fields['categories'].queryset = Categories.objects.filter(users=user)
and instantiate it with:
form = InstrumentSearchForm(user=request.user)
Does that help at all?

displaying initial data in dropdown list in django

I am writing an app in django1.4 to show the Lessons and Courses.I wanted to give an edit_lesson view in which the Course can be selected by the user.When the edit page is displayed,the Course associated with the Lesson should be shown as default selected.
I tried to write the view like this
def get_form_data(request):
return request.POST if request.method == 'POST' else None
def edit_lesson(request,id,template_name):
lesson = get_object_or_404(Lesson,pk=id,author=request.user)
form_data = get_form_data(request)
course_choices_form = CourseChoicesForm(form_data)
...
context = {'course_choices_form':course_choices_form,...}
if request.method == 'POST' and ....:
...
#if GET method ,display the form with initial data
course_choices_form = CourseChoicesForm(initial={'courseoption':lesson.course})
context.update({'course_choices_form':course_choices_form})
print "context['course_choices_form'].initial=",context['course_choices_form'].initial
return custom_render(request,context,template_name)
The CourseChoicesForm is like
class CourseChoicesForm(forms.Form):
courseoption = forms.ChoiceField(choices=[],required=False,label='Course')
def __init__(self, *args, **kwargs):
super(CourseChoicesForm, self).__init__(*args, **kwargs)
self.fields['courseoption'].choices = [(x.id,x.title) for x in Course.objects.all()]
In the edit_lesson template I am displaying the course_choices_form as
{{ course_choices_form.as_p}}
Still ,the drop down list does not show the lesson's course but just the first entry in the Course.objects.all()..
Can someone tell me what I am doing wrong?
Here's what I'm doing:
class CourseChoicesForm(forms.ModelForm):
courseoption = forms.ModelChoiceField(Courses.objects.all())
The Django engine take care for you of making the list of tuples to fill the ChoiceField. The Courses.objects.all() can be any queryset.
https://docs.djangoproject.com/en/dev/ref/forms/fields/#fields-which-handle-relationships

int() argument must be a string or a number, not 'QueryDict'

I'm rendering out 3 multiple select boxes on my form.
I'm filtering each box out to have a seperate type of day.
When I submit my form I get this error.
int() argument must be a string or a number, not 'QueryDict'
What must I do to save my form?
This is what i'm doing on my forms.py file to get the different filtering for each select box.
class ContractForm(forms.ModelForm):
def __init__(self, project_id, *args, **kwargs):
super(ContractForm, self).__init__(*args, **kwargs)
self.fields['shoot_day'].queryset = Day.objects.filter(type=SHOOT, project__id=project_id)
self.fields['travel_day'].queryset = Day.objects.filter(type=TRAVEL, project__id=project_id)
self.fields['additional_day'].queryset = Day.objects.filter(type=ADDITIONAL, project__id=project_id)
I'm getting my project_id like so:
def editcontract(request, contract_id, slug):
context_dict = {}
contract = get_object_or_404(Contract, pk=contract_id)
if request.method == 'POST':
form = ContractForm(request.POST, instance=contract)
if form.is_valid():
form.save()
TvUsageForm = TvUsageFormSet(request.POST, instance=contract)
AdditionalMediaUsageForm = AdditionalMediaUsageFormSet(request.POST, instance=contract)
TvUsageForm.save()
AdditionalMediaUsageForm.save()
return HttpResponseRedirect(reverse('contract_list', kwargs={'slug':slug}))
else:
form = ContractForm(instance=contract, project_id=contract.project_id)
TvUsageForm = TvUsageFormSet(instance=contract)
AdditionalMediaUsageForm = AdditionalMediaUsageFormSet(instance=contract)
project = get_object_or_404(Project, slug=slug)
context_dict = { 'form': form,
'tvusage_form':TvUsageForm,
'additional_form':AdditionalMediaUsageForm,
'project':project
}
return render_to_response('contracts/edit_contract.html', context_dict, RequestContext(request))
You have a confusion with the argument list and keyword arguments:
Instead of:
ContractForm(instance=contract, project_id=contract.project_id)
You want:
ContractForm(contract.project_id, instance=contract)
To elaborate: Your constructor accepts the project id as first argument not as keyword argument. Thus you need to give it as first argument. Simple confusion, eh?
Maybe this help you: Adding data to many-to-many field of a modelform within a view

is_valid always False (Django)

I have the following form with dynamic fields:
1) In models.py I want to pass in a value to the form to query
class InsertValuesForm(forms.Form):
def __init__(self, idfield, *args, **kwargs):
super(InsertValuesForm, self).__init__(*args, **kwargs)
for f in Parameter.objects.filter(id=idfield):
if Part.objects.get(parameter=f.parameter_name).isfunction:
self.fields.update({
f.parameter_name) : forms.CharField(widget=forms.TextInput() )})
1) In views.py
def something(request)
#......
idfield = request.GET.get('feid','0')
form = InsertValuesForm(request.POST,idfield)
if request.method == 'POST':
if form.is_valid():
#some code
else:
form = InsertValuesForm(idfield)
return render_to_response('fuzz/configuration.html', {
'form': form,
},context_instance=RequestContext(request))
In number 1 situation, I was able to display the dynamic fields in the for loop. However, the form threw me this error after filling up all of the fields and submitting(POST):
int() argument must be a string or a number, not 'QueryDict'. I was thinking it is the request.POST that is causing the error.
after doing some research on this problem, there were similar solutions like this:
http://groups.google.com/group/django-users/browse_thread/thread/ddefd76324ffe6cd
http://groups.google.com/group/django-users/browse_thread/thread/495a917396b20b37/c430d71a31204e5d#c430d71a31204e5d
2) In models.py
class InsertValuesForm(forms.Form):
def __init__(self, *args, **kwargs):
idfield = kwargs.pop('idfield', False)
super(InsertValuesForm, self).__init__(*args, **kwargs)
for f in Parameter.objects.filter(id=idfield):
if Part.objects.get(parameter=f.parameter_name).isfunction:
self.fields.update({
f.parameter_name) : forms.CharField(widget=forms.TextInput() )})
and
the following snippet of views.py(same as number 1)
def something(request)
#......
idfield = request.GET.get('feid','0')
form = InsertValuesForm(request.POST,idfield)
if request.method == 'POST':
if form.is_valid():
#some code
else:
form = InsertValuesForm(idfield)
return render_to_response('fuzz/configuration.html', {
'form': form,
},context_instance=RequestContext(request))
Now the above code doesn't even display the dynamic textboxes and is just displayed as blank page. Appreciate if anybody can shed some light on
how to display these dynamic textboxes and at the same time,
getting the values of these textboxes via request.POST and also making the form validate. Thanks
You have changed the signature of the form's __init__ so that the first positional parameter is idfield. Don't do that, because now when you instantiate it with form = InsertValuesForm(request.POST,idfield), it's taking the first parameter to be idfield, rather than request.POST.
Instead, define the method like this:
def __init__(self, *args, **kwargs):
idfield = kwargs.pop('idfield', None)
...etc...
and instantiate it with a keyword arg:
form = InsertValuesForm(request.POST, idfield=idfield)