Django dynamic form rendering - python

I'm stuck with a task I have currently with django. There are plenty of tutorials on creating dynamic forms but my problem is more about getting a proper HTML.
I have several model instances, let is be
class SomeModel(models.Model):
field1=models.CharField(max_length=20)
field2=models.CharField(max_length=20)
What I need is to show user an HTML page whith multiple forms representing several SomeModel instances.
The problem is I wish that only some of the forms will give user an opportunity to enter only field1, some will only allow to enter field2 and some give both.
For the fields I don't wish to be editable I want to present it's content as a label. So, for instance in my database I have tree SomeModel instances that have field1 and field2 ('aaa','bbb'), ('cccc','dddd') and ('eeeee','fffff'). And I have information that I want only field1 editable in first instance, on the second only field 2 is editable, and it is allowed to edit both field1 and field2.
The HTML that renders it I want looks like somewhat like this
<form method="post" action="">
<input name="some_model_id" type="hidden" value="0">
<label>some Model 0 field1</label><input type="text" name="someModel-0-field1" value="aaa" id="id_form-0-title" />
<label>bbb</label>
<input name="some_model_id" type="hidden" value="1">
<label>cccc</label>
<label>some Model 1 field2</label><input type="text" name="someModel-1-field2" value="dddd" id="id_form-0-title" />
<input name="some_model_id" type="hidden" value="2">
<label>some Model 2 field1</label><input type="text" name="someModel-2-field1" value="eeeee" id="id_form-0-title" />
<label>some Model 2 field2</label><input type="text" name="someModel-2-field2" value="fffff" id="id_form-0-title" />
<input name="Submit" type=submit value="Submit">
</form>
I want to have the reciving the data from the forms as django usualy does, validation, etc.
I know for several forms there are formsets, but I don't know how to use them here.
Also I wish I could first create a form and then say what I want to edit instead of passing this information to __init__.
What is the pythonic way to implement this?
Thank you!

Related

HTML, how to auto select the date time picker from sql database

I've a HTML form for editing existing data.
Let's say today is 10/06/2022 18:05 and i want to edit my course date time in my web app.
My course date on the data base is 21/08/2023 10:00. I want to change it to 22/08/2023 10:00. When I open my from on the web app all the inputs came with the existing data already selected. But date time picker comes as 10/06/2022 18:05. I've set the value as the date attribute of course object but it's not working. This works for the rest of the inputs but not for the datetime input.
I basically need the html date time picker comes with autoselected with the existing saved data <course.date> .
I'm writing this web app on python flask and using a postgresql for database. The other inputs comes with selected values but not datetime input.
Anyone has any ideas how to approach this one?
<form action="/courses/{{course.id}}" method="post">
<label for="course">Course Title</label>
<input type="text" name="title" value="{{course.title}}">
<label for="date">Date</label>
<input type="datetime-local" name="date" value="{{course.date}}">
<label for="capacity">Capacity</label>
<input type="number" name="capacity" value="{{course.capacity}}">
<label for="active">Active</label>
<select name="active">
<option value="True">Active</option>
<option value="False" {% if course.active == False %} selected {%endif%}>Deactive</option>
</select>
<input type='submit' value="Update Course">
</form>
If I am understanding the issue right:
course_date in the database is: 21/08/2023 10:00
course_date in the app remains as the local-current time: 10/06/2022 18:05 (example)
GET request properly loads data from the database into the other fields except course-date
you've tried making a POST request to update course_date, but the field doesn't change
My suggestion to debug this is to look at the responses to your GET request. What do they come out as?
Inside your GET request's response,
if the course-date is 21/08/2023 10:00, that means your problem is in your javascript or the code that plugs in your field value inside the HTML. Your frontend field is simply ignoring the response from flask or the data is not being mapped/handled right
if the course-date is 10/06/2022 18:05 or is null. That means your flask backend is broken, double-check the flow of your data from the SQL select -> storing the data in a python variable -> sending the data out
Also remember to Hard-Reload.
Based on our exchange in comments, it looks like the issue is with the date format being passed in your template.
Changing:
<label for="date">Date</label>
<input type="datetime-local" name="date" value="{{course.date}}">
To:
<label for="date">Date</label>
<input type="datetime-local" name="date" value="{{course.date.isoformat()}}">
Should correct the problem for you.

multiple inputs of the same name in an html form

I have some html code that contains a form. When submitted it sends a post request to a server. The form has various inputs, each with a name and a value, however there are some inputs with the same name.
Here is an example of what I mean:
<form action="http://example.com" method="post">
<input name="name" value="val">
<input name="name" value="val">
<input type="submit">
</form>
First, I am confused as to how there can be two values of the same name. Please note that I have tried removing one of the instances of <input name="name" value="val"> however this returns an error so it seems that both instances are needed.
Second, I am trying to convert this to a python request using the request library.
I have the following request:
requests.get(url = URL, params = PARAMS).json()
Where PARAMS is a dictionary of the various inputs. For example:
PARAMS = {'name':"val"}
However, being a dictionary, I can't have multiple instances of the same value. How do I make this work? Thanks
If there are duplicated names then the values will be in an array with the name. The demo below sends to a live test server and the response is directed to an <iframe>
<form action="https://httpbin.org/post" method="post" target="response">
<input name="name" value="val">
<input name="name" value="val">
<input type="submit">
</form>
<iframe name='response'></iframe>
What you are looking for is to use input arrays. With them, you can have many inputs sharing the same name, and in the server side, the data will be treated as an array. So the HTML would be:
<form action="http://example.com" method="post">
<input name="name[]" value="val1">
<input name="name[]" value="val2">
<input type="submit">
</form>

How to structure form data within MongoDB (Python/Flask)

I am having trouble structuring my data within MongoDB from user forms.
My ideal document structure is this:
As you can see the ingredients are within an array that would be iterable.
However I cannot work out a way when submitting my form to do this. My form for the ingredients section looks like this:
<h4>Ingredients</h4>
</div>
<div class="row">
<div class="input-field col s6">
<input id="ingredients_1_name" name="ingredients_name_1" type="text" class="validate" required>
<label for="ingredients_1_name">Ingredient</label>
</div>
<div class="input-field col s3">
<input id="ingredients_1_quantity" name="ingredients_quantity_1" type="text" class="validate" required>
<label for="ingredients_1_quantity">Quantity</label>
</div>
<div class="input-field col s3">
<input id="ingredients_1_unit" name="ingredients_unit_1" type="text" class="validate" required>
<label for="ingredients_1_unit">Unit</label>
</div>
</div>
The user is able to press a JavaScript button that adds a new row with the name "ingredients_2_name" and so on. This leads to a very unstructured DB:
This is obviously a mess which when it comes to using the data requires an unnecessary amount of manipulation.
I can't seem to find any information online about how to send data from a HTML form to MongoDB in a defined way.
Currently on form submission, the view looks like this:
#app.route('/insert_recipe/', methods=['GET','POST'])
def insert_recipe():
"""
This function is called when a user clicks the submit button on the add
recipe form. Uses the insert_one() method to add to the recipes document.
"""
recipes = mongo.db.recipes
dictionary = recipes.insert_one(request.form.to_dict())
return redirect(url_for("get_recipes"))
This simply takes the input names as keys and the user input as values.
Is anyone able to describe how I am able to store form data within MongoDB in a structured way?
What you require is to convert a plain HTML-form-post request into a JSON-like structure without any data manipulations. I highly doubt that it's even possible, because JSON-objects use nested data and a key/index approach to access it and HTML-form-post data is flat and follows unique-id-approach to access it's data. I can see 2 possible solutions:
Use serialization library WTForms which will do python-data -> html-form -> python-data conversion for you and you wouldn't have to do an unnecessary amount of manipulation by yourself.
Make a webpage (a front-end) post request for you as a JSON-object.

Python request input's id from a form

I use google app engine and python. I want to retrieve the id of an input and not the value. If I use self.request.get("thename") I get the value of the input.
Here is the html
<form method="post">
<input value=" " type="submit" name="thename" id="thenumberIneed"/>
</form>
I cannot put my data on the value tag because I have an image as a background on the input and if I enter there anything, the data shows infront of the image. So, I keep value empty.
If you don't want the value to show, change it to:
<input type="hidden" ... />
But I suspect there are other problems you should be solving, like why does your image get in the way of showing values in the page, and what kind of data you want to retrieve.
You shouldn't be using the id for this type of logic.
You would have better luck using a seperate hidden input field, for example.
<input type='hidden' name='myval' value='thenumberyouneed' />
And then you can just do your search for myval and get your answer.

Retrieving form field attribute in django

I have an input text field in my form which has an important new attribute added via JavaScript. The attribute name is fieldid.
Is there a way to retrieve this attribute and its value from the view after the form is summited?
Attributes on form elements are not passed on to the server when forms are submitted; only input element values are.
The way to add extra information to be sent back to a server on a form submit is by adding additional <input /> elements to your form, specifically <input type="hidden" /> elements.
E.g.
<input type="hidden" name="foobar" value="spam and eggs" />
adds a new field foobar to your form data with the value spam and eggs.

Categories