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

Date: April 21st 2016
Last updated: April 21st 2016

I have been filtering querysets in each form to provide the most appropriate content for each user. Then I discovered this error when submitting a form:

Error message: int() argument must be a string or a number not QueryDict

This error had gone unnoticed until I was actually submitting data. That is, the drop down modelchoicefield was working as it should from a filtering standpoint. It just failed at the most important part, submitting data.

In the following example I wanted to allow a surfer to choose ONLY from her/his own boards list for a diary entry. I used __init__ method to provide a filtered queryset.

forms.py

class SurfDiaryForm(forms.ModelForm):

    class Meta:
        model = SurfDiary
        fields = ['starttime',
                #<- snipped ->]

    def __init__(self, current_user, *args, **kwargs): #user=None,
        super(SurfDiaryForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        #<- snipped ->
        self.fields['board'].queryset = Board.objects.filter(surfer__user=current_user)

views.py
I found the solution here: http://stackoverflow.com/questions/6649499/int-argument-must-be-a-string-or-a-number-not-querydict.

The main point being that I hadn't provided the post form a surfer.user.id. It is important that the surfer.user.id takes the first positional argument in SurfDiaryForm, NOT the second after request.POST.

@login_required
def diaryentry(request, surfer_id):
    surfer = get_object_or_404(Surfer, pk=surfer_id)
    if request.method == "POST":
        # ORIGINAL CODE
        #form = SurfDiaryForm(request.POST)

        # MODIFIED TO...
        form = SurfDiaryForm(surfer.user.id, 
                             request.POST)
        # ORIGINAL CODE
        if form.is_valid():
            diary = form.save(commit=False)
            diary.user = get_object_or_404(User, pk=request.user.id)
            diary.save()
            return redirect('/{}/diary'.format(surfer_id))
    else:
        form = SurfDiaryForm(current_user=surfer.user.id)
    return render(request, 
                  'surferprofile/adddiaryentry.html',
                  {'surfer': surfer, 'form': form})

results matching ""

    No results matching ""