Django request.POST not passed to


I have a form, but request.POST is not passing data to my form. i.e. is empty

my form

class DPStatusForm(forms.Form):
    status = forms.ChoiceField(label="")

    def __init__(self, excluded_choice=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if excluded_choice:
            status_choices = (
                (s.value, s.label)
                for s in DP.Status
                if s.value != excluded_choice
            status_choices = ((s.value, s.label) for s in DP.Status)

        self.fields["status"].choices = status_choices

view to receive form data

def update_status(request, id):
    if request.method == "GET":
        return redirect("my_app:show_dp", id)

    p = get_object_or_404(DP, pk=id)
    form = DPStatusForm(request.POST)
    # debug statements
    # ...

With the 2 print statements, I can see that request.POST is present with status key populated, but is empty:

# request.POST
<QueryDict: {'csrfmiddlewaretoken': ['xxx...], 'status': ['1']}>
<MultiValueDict: {}>

Why is not getting populated?

>Solution :

Check the value of excluded_choice. You’re defining an extra positional argument to the form __init__ method which is intercepting the data you are trying to pass to the form.

The simplest solution I see would be to modify the form __init__ method slightly.

    def __init__(self, *args, excluded_choice=None, **kwargs):

or pass the data as a key-word argument.

form = DPStatusForm(data=request.POST)

I think the first is preferable as it preserves the expected behavior of the form class.

Leave a Reply Cancel reply