Additional field in django form

2019-06-26 03:05发布

问题:

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 fields, but an additional one.

So that I can later do something like (pseudocode):

def form_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            extra_field = form.cleaned_data['extra_field']
            #or maybe
            extra_field = form.extra_field
            #...
    else:
        form = MyForm()
        #...

Anything that might work in order to pass an extra property, which is not a field but a simple variable, to the POST request.

回答1:

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

<input type="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)


回答2:

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.



回答3:

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 }}
   <input type="hidden" name="extra_field" value="{{ extra }}" />
   <input type="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.