Home > Blockchain >  Django request.POST not passed to form.data
Django request.POST not passed to form.data

Time:01-17

I have a form, but request.POST is not passing data to my form. i.e. form.data 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
            )
        else:
            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
    print(request.POST)
    print(form.data)
    # ...

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

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

Why is form.data not getting populated?

CodePudding user response:

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.

  • Related