Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django request.POST not passed to form.data

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading