How to convert form data to django? - django

How to convert form data to django?
I have a html formalary that sends several arrays given. for example:
<input name="item[0]nome"/>
<input name="item[0]descriaco"/>
<input name="item[1]nome"/>
<input name="item[1]descriaco"/>
This comes from the html form
With this I can pass the data to a view in Django using post and at the same time pass an is_valid. Goodbye then.
When trying to grab the dest object items as array, I came across a problem.
The Django Form returns me the key with the name "item[0]name"
Instead of returning an array with:
item[{
"nome": value,
"descricao": value},
{
"nome": value,
"descricao": value}
]
Thank you for attention.

I got it sorted out.
<input name="nome"/>
<input name="nome"/>
<input name="nome"/>...
itens=[]
for item in request.POST.getlist('nome'):
itens.append({
'nome': item
})
Thank you Lemayzeur and cezar

Related

Form Validation On Frontend or Backend Django

I have an HTML form with a date field:
<input type="date" class="form-control" placeholder="Date" name="date" autocomplete="off" required>
Before submitted the form, I want to ensure that the date that was entered is greater than the current date. If it is older, then I want to show a custom form validation to say something like, "You must enter a date past today.".
Do you suggest I do this validation on the backend or the frontend? Thanks!!
I think you're better off doing in within django forms. The reason is, if you do it in the front-end, you'll have to repeat the code when applying this property elsewhere.

Obtaining ID of form in a formset

I need a way to set the id of the div that contains each form in a formset to a value that contains a number that is representative of the index of that form.
eg. I want the 2nd form to have a parent div that looks like this
<div id="1"> #id could even be "id_form-1-id".
form
</div>
I've found that {{form.id}} produces the following:
<input type="hidden" name="form-3-id" id="id_form-3-id">
Is there a way that I can extract just the id value (i.e. id_form-3-id) from this string using a template tag?
For reasons that I won't get into, a forloop.counter counter won't reliably return an index as some forms within the formset can be created outside of the typical formset for loop.
Thanks!
You can use auto_id:
{{form.id.auto_id}}

In Django how to getbinary field data from POST form

I have one HTML file, where I am using one image upload button. Now this image is stored in the MySql database as Blob. I need to get or read this image data somehow in Django through post method. Can anyone please help how to do?
Icon is defined like :
icon = models.BinaryField(null=True)
My Html:
<input type="file" id="toolicon" accept="image/*" data-type='image' >
<button id="OpenImgUpload" style="margin-left: 100px">Image Upload</button>
In JQuery:
$('#OpenImgUpload').click(function(){ $('#toolicon').trigger('click'); });
Image:
Now I want to get this file as Binary Field data. Till now I have used :
tool_icon = request.POST('toolicon', '')
tool_icon = request.POST.get('toolicon', '')
tool_icon = base64.b64encode('toolicon', '')
Nothing works ... Can any one please help me.
Uploaded files are contained in request.FILES with the key corresponding to the name attribute on the input element.
So you should add a name attribute to your input:
<input type="file" name="toolicon" ...
And then access the data using request.FILES:
tool_icon = request.FILES.get('toolicon', '')
The request must have a content type of multipart/form-data which you should set on your form:
<form enctype="multipart/form-data" ...

data How to keep form when user gets redirected back to the form when they fail a validation (Python, Django)?

I know this might be a duplicate question, but the previous one was an older question and those questions uses a form instance which doesn't really help me.
How do I keep my form data after a failed validation? I have multiple dropdowns and input fields and I hate to see my users re-do and re-type everything when they fail validation in the backend. Let's say I have this very simple form:
HTML:
<form class="" action="/register" method="post">
<label for="">First Name</label>
<input type="text" name="" value="">
<label for="">Last Name</label>
<input type="text" name="" value="">
<label for="">Password</label>
<input type="password" name="" value="">
</form>
views.py:
def register(self):
.....
if errors:
for err in errors
messages.errors(request, err)
return redirect('/')
else:
messages.success(request, "Welcome User!")
return redirect('/dashboard')
Most examples that I came across were using the form instance which uses form.save() etc. I opted out on that one. Is there a way to auto-populate my form with the data that the user submitted if they were to fail validation? Thanks!
Django form classes are the way to go. Form validation and rendering are the tasks they were build for. I would strongly recommend using them, because they also take care of security aspects, when it comes to passing user input back to the browser (all input from user land is evil!).
If you really need to achieve this without form classes, you need to add the form values to your rendering context manually - this allows you to use them in your template.
The main problem with your approach is, that you want to redirect in case of validation error. A redirect is a response to the browser that tells: I have nothing for you, please go to this location. Usually the browser does not post the data send in the first request also to the second one (which is generally a good behavior). You may work around that by answering with status code 307 instead of 302. Read e.g. Response.Redirect with POST instead of Get? for more information. Alternatively you may encode your form data into the target location using get parameters.
Again: You should have a very good reason to not just use the django approach of one view that acts on GET and POST different and handles the form properly using the form instance.

How to post a array to views.py

I am using for loop in my template and for different id of each record i am using arrays
{% for item in product %}
<div class="register_div">
<p><label for="id[{{ item.id }}]">{{ item.Name }} </label> <input type="text" name="custom[{{item.id}}]"/></p>
</div>
{% endfor %}
Now when in my views i want to save this data to my database.But firstly i checked that whether my array return something or not.So i just try print that as.
q = upload_form.data['custom[]']
or
q = upload_form.data['custom']
but it gives me this error
"Key 'custom[]' **OR** key custom not found in <QueryDict: {u'custom[2]': [u's'], u'custom[1]': [u'a'], u'price': [u''], u'title': [u''], u'customatt': [u'', u''], u'csrfmiddlewaretoken': [u'up4Ipd5L13Efk14MI3ia2FRYScMwMJLz']}>"
but if i print this
q = upload_form.data['custom[1]']
then it display the value of array 1.
so please suggest me a better way to do this how i can display all values inside my array in views.py
As upload_form.data is a dictionary, the key 'custom[]' simply doesn't exist. Try something like:
custom_values = {}
for key, value in in upload_form.data.items():
if key.startswith('custom'):
custom_values[key]=value
The dictionary custom_values holds now all your 'custom' form values.
This is not an answer to question, but:
You are not posting an array, but different inputs whose name looks like accessing array. e.g. you are posting different input variables named custom[1], custom[2] etc. But custom is not an array, you will have to access inputs as custom[1] etc.
I'm not sure you want this or not!