nimbit
nimbit

Reputation: 83

Field 'id' expected a number but got <QueryDict: >error in django

I have this form:

class addMeal(forms.Form):
    name = forms.CharField(
        max_length=40,
        widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'})
    )
    foods = forms.ModelMultipleChoiceField(
        queryset=Food.objects.none(),
        widget=forms.SelectMultiple(attrs={'class':'form-control'})
    )
    def save(self,request):
        data = self.cleaned_data
        meal = Meals(name=data['name'],user=request.user,foods=data['foods'])
        meal.save()
    def __init__(self, user=None,*args, **kwargs, ):
        super().__init__(*args, **kwargs)
        if user is not None:
            self.fields['foods'].queryset = Food.objects.filter(user=user)

    class Meta:
            model = Meals

and this view:

@login_required
def addmeal(request):
    if request.method == 'POST':
        form = addMeal(request.POST)
        if form.is_valid():
            form.save(request)
            return redirect('food:index')
    else:
        form = addMeal(user=request.user)      
    return render(request,'addmeal.html',{'form':form})

when i fill out form and press submit django give me error(Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['C2B8y3kLCa5IQ0S5Mvk7Tw0NTU4pNlYicppWlsIL1LCrcc8AuCQzjJkqWNUot4z6'], 'name': ['شام'], 'foods': ['1']}>.). what should i do to fix it?

Upvotes: 1

Views: 1118

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

Since user is the first parameter, you pass the data as second, so:

@login_required
def addmeal(request):
    if request.method == 'POST':
        form = addMeal(user=request.user, data=request.POST)
        if form.is_valid():
            form.save(request)
            return redirect('food:index')
    else:
        form = addMeal(user=request.user)      
    return render(request,'addmeal.html',{'form':form})

Upvotes: 1

Related Questions