Skip to content Skip to sidebar Skip to footer

Additional Field In Django Form

I am creating a form in Django. When I POST the data, the data is naturally sent. My problem is, I want to pass an additional property to the POST data, that is not any of the form

Solution 1:

If you want to pass anything to django as a POST request from the HTML, you would use a hidden input

<inputtype="hidden" name="foo" value="bar" />

print request.POST['foo'] # out: bar

If you want to modify the POST dictionary in python from your view, copy() it to make it mutable.

mutable_post = request.POST.copy()
mutable_post['foo'] = 'bar'

form = MyForm(mutable_post)

Solution 2:

There are a few ways to do this. One, is you can just add it to your template.

<form action="." method="post">{% csrf_token %}
   {{ form.as_p }}
   <inputtype="hidden" name="extra_field" value="{{ extra }}" />
   <inputtype="submit" value="submit" />
</form>

Another way is to add the field to your form class, but use a hidden widget. I'm not sure if this is what you want. If it is, just add a comment and I can explain this point further.

Solution 3:

In your form's clean method, you can add new information to the cleaned_data, something like: form.cleaned_data['extra'] = 'monkey butter!', then if the form.is_valid(), you have your extra info.

What you do finally will depend on what your extra information is, and where it is available to you.

Post a Comment for "Additional Field In Django Form"