Home > OS >  Django - Error when I filter my form field's queryset
Django - Error when I filter my form field's queryset

Time:11-05

I created a form and view (FBV) to add new model. I overrided form's __init__ but now when I try to access my view it raise an error CreationForm' object has no attribute 'get'

My view :

def Creation(request):
    user = None
    if request.user.is_authenticated:
        user = request.user

    #   POST METHOD
    if request.method == "POST":
        form = CreationForm(request.POST)   
        form.user = user    
        if form.is_valid():
            sheet = form.save()
            return redirect("sheet_detail", pk=sheet.id)

    form = CreationForm(initial={'user': request.user})
    return render(request, "jde/creation_form.html", context={"form": form})

My form :

class CreationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CreationForm, self).__init__(self, *args, **kwargs)
        self.fields["contest"].queryset = Contest.objects.filter(active=True)

    class Meta:
        ...

CodePudding user response:

The error is being raised because you're passing self to the call to super().__init(). Removing it should solve your problem.

class CreationForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CreationForm, self).__init__(*args, **kwargs)
        self.fields["contest"].queryset = Contest.objects.filter(active=True)

    class Meta:
        ...
  • Related