Extra field in django form

I am creating a form in Django. When I send data, the data is naturally sent. My problem is that I want to pass an additional property to the POST data, which is not one of the form fields, but another.

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

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 can work to pass an additional property, which is not a field, but a simple variable, into a POST request.

+4
source share
3 answers

If you want to pass something to django as a POST request from HTML, you should use hidden input

 <input type="hidden" name="foo" value="bar" /> print request.POST['foo'] # out: bar 

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

 mutable_post = request.POST.copy() mutable_post['foo'] = 'bar' form = MyForm(mutable_post) 
+4
source

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

What you do will ultimately depend on what additional information and where it is available.

+2
source

There are several ways to do this. First, you can simply 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 a field to the form class, but use a hidden widget . I am not sure if this is what you want. If so, just add a comment and I can explain this question further.

+1
source

Source: https://habr.com/ru/post/1384433/


All Articles