can i do process with form django python - python

there is a input and select with options in form tag. i want to get input value and option that entered. and i will do somethings on backend with python that value and option than i will return a result to website. but i dont use to forms.py. how can i do? is it possible?
<form action="" method="post">
{% csrf_token %}
<input type="text" name="getinputValue">
<select name="">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<button type=""class=""></button>
<p>{{result}}</p>
</form>

So, from what I understanding in your question, you want to retrieve the data from the form in your views and do something with it. You will have to give your <select> a name attribute so that you can reference it in your views.
<select name="level">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
In your views, one of the ways you can retrieve this data is by:
def options_view(request):
level = request.POST.get('level') # get name of option as specified in the <select> tag
# here you can do something with it
print(level)
return render(request, 'home.html', {'level': level})
This is one way to do it.

Related

Problem with select and request.form.get and getlist in Flask

My problem is not that serious, just a little bit annoying. I have a dropdown menu and a list of values; however, my values resets themselves to the first option, and I would like for them to remain as the user selected them.
I have read from other sources that the solution is using getlist instead of get, but when I attempt to do it, I get the following error:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
I have little experience working with flask and Jinga. I guess this must be a problem with the type of values, or some type of name or value that I need to fetch... I honestly have no idea. Any help will be appreciated.
Here is the video of how the flask is working with request.form.get, and here is the code that I have for that specific html view and the fragment of the app where I am requesting the data.
#app.route('/apuntual', methods = ['GET','POST'])
def apunt():
if request.method == 'POST':
# This is the button that I click on the video
if request.form.get('capturar') == 'capturar':
sample_rate_unf = request.form.get('f_muestreo')
samples_to_acq_unf = request.form.get('m_canal')
#Changing the values to int so I can work with them
sample_rate = int(sample_rate_unf)
samples_to_acq = int(samples_to_acq_unf)
#lots of more code in here
#
# Sending the output values to make the graph, and some other values to
# display in the html
return render_template('apuntual.html', fmax = fmax, tad = tad, imagen = datos)
<div class="col-md-2">
<form method="POST">
<h5 class="mb-1">Frecuencia de muestreo</h5>
<select name="f_muestreo">
<option value="2048">2048</option>
<option value="2560">2560</option>
<option value="3200">3200</option>
<option value="5120">5120</option>
</select>
<h5 class="mb-1">Muestras por canal</h5>
<select name="m_canal">
<option value="2048">2048</option>
<option value="4096">4096</option>
<option value="8192">8192</option>
</select>
<h5 class="mb-1">Captura instantánea</h5>
<p class="bs-component">
<input type="submit" class="btn btn-primary" name="capturar" value="capturar">
<input type="submit" class="btn btn-primary" name="borrar" value="borrar">
</p>
<p class=""bs-component>Frecuencia máxima de: {{ fmax }} Hz con TAD: {{ tad }} ms.</p>
</form>
</div>
One solution I can think of is to pass the selected option as a variable to the template and mark the selected option in the template. Here is a demo:
#app.route("/", methods=("GET", "POST"))
def demo():
options = (1, 2, 3, 4)
selected = None
if request.method == "POST":
selected = int(request.form.get("something"))
# Rest of the code goes here
return render_template("demo.html", options=options, selected=selected)
<form method="POST">
<select name="something">
{% for op in options %}
{% if selected == op %}
<option value="{{ op }}" selected>{{ op }}</option>
{% else %}
<option value="{{ op }}">{{ op }}</option>
{% endif %}
{% endfor $}
</select>
<input type="submit">
</form>
Notice that I put all the options as a tuple in the server code. One of reason is to avoid repetitions in the template code. It is also generally considered a bad practice to store data directly to the frontend code like what you are doing here. My demo is not perfect either. A better solution is to put all these options into a configuration file.

django forms print select values

I am trying to return the selected choice value from a dropdown menu in django. The option (in html) is dynamically populated from the database's model primary key.
HTML
<form class="student-ID-search" action="{% url 'new_coach_schedule' %}" method="post" >
<select class="form-control" id="student_select">
<option>Select student ID</option>
{% for student_data in students_data %}
<option value="{{ student_data.pk }}">{{ student_data.pk }}</option>
{% endfor %}
</select>
</form>
<button class="btn" type="submit" name="search_result" value="select>
<i class="fa fa-search"></i>
</button>
views.py
students_data = Student.objects.all()
search_result = NewStudentSearchForm(request.POST)
if 'search_result' in request.POST:
test_print_to_screen = search_result['student_select']
print(test_print_to_screen)
args = {'students_data': students_data}
return render(request, 'static/html/new_coach_schedule.html', args)
else:
return render(request, 'static/html/new_coach_schedule.html', args)
forms.py
class NewStudentSearchForm(forms.Form):
search_field = forms.CharField(max_length=50) # This is for something else.
student_select = forms.ModelChoiceField(queryset=Student.objects.all(), empty_label=None)
When I make use of ModelChoiceField, test_print_to_screen does not print out the selected choice that I chose in the html select box.. It prints out everything instead.
EG:
<select name="student_select" id="id_student_select">
<option value="5">Student object (5)</option>
<option value="6">Student object (6)</option>
<option value="7">Student object (7)</option>
<option value="8">Student object (8)</option>
<option value="9">Student object (9)</option>
<option value="10">Student object (10)</option>
<option value="11">Student object (11)</option>
<option value="12">Student object (12)</option>
<option value="13">Student object (13)</option>
</select>
How can I go about in my forms.py so that when i select the value in my browser, it will return / print out the selected choice back to me?
Update
As per the comments, I updated my views.py file to include cleaned_data as follows:
if 'search_result' in request.POST:
search_result = NewCoachSearchForm(request.POST)
print(search_result)
if search_result.is_valid():
test = search_result.cleaned_data['student_select']
print(test)
else:
print(search_result.errors)
However, this produces a stacktrace error:
<ul class="errorlist"><li>student_select<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
When using Django forms, please call form's is_valid() method and then if it is valid use cleaned_data attribute to access submitted values.
students_data = Student.objects.all()
search_result = NewStudentSearchForm(request.POST)
if search_result.is_valid():
cd = search_result.cleaned_data
selected_student = cd['student_select'] # Here you get Student instance

Jinja2 to put a whole element in <option>

I need to dynamically select from the following:
So that I can show the selected element depending on POST request.
I want to templatize selected="selected" so that I can choose where to put.
<select name="my_name">
<option value="5min">5-Min</option>
<option value="1hour" selected="selected">Hour</option>
<option value="1day">Day</option>
</select>
Assume target is the desired value that you want to select (obtained from the POST dictionary).
Then you need two things:
Prepare a dictionary containing value - display text pairs for all options in the select, e.g
mydict = {'5min': '5-Min', '1hour': 'Hour', '1day': 'Day'}
In yourtemplate.html:
<select name="my_name">
{% for key, value in mydict.items() %}
<option value="{{key}}"
{% if (key == target) %} selected="selected" { %endif %}
>
{{value}}
</option>
{% endfor %}
</select>
How to pass the target - in your view you need to do this (I assume you know the basics of views in Flask)
target = request.form['key_of_the_data_we_need'] # the value that should be selected
mydict = {'5min': '5-Min', '1hour': 'Hour', '1day': 'Day'} # helper for the select
return render_template('yourtemplate.html', target=target, mydict=mydict)
This way, the data is sent to yourtemplate.html which contains the code discussed above, therefore selecting the desired <select> option.
Using the same approach as Pawel did, I just changed some small things in order to work with my actual version of Jinja2:
<select class="form-control" id="worker" name="worker">
{% for key in workers %}
<option value="{{key}}" {% if key == people.worker %} selected="selected" {% endif %}>
{{key}}
</option>
{% endfor %}
</select>
And from the controller:
workers = {'First One','Second One', 'Third One'}
return render_template('edit.html', people=people, workers=workers)
Remember to put the controller code within the controller which is passing the data for the view.
It is not totally clear to me what the background of your question is. If the reason is that you can't use wtf.quick_form(yourform) because you need some customization, you could simply use
{{ form.workers.__call__(**{'class': 'form-control'}) }}
for the respective field in your Jinja2 template. This selects the posted element in the form. Note how I define additional attributes (a class).
The result will be (for example):
<select class="form-control" id="worker" name="worker">
<option value="0">text1</option>
<option selected value="1">text2</option>
<option value="2">text3</option>
</select>
This of course requires that you have a properly defined form:
class yourform(FlaskForm):
workers = SelectField(
'name',
validators=[Required()],
choices=[(0, 'text1'), (1, 'text2'), (2, 'text3')],
coerce=int
)
(... whatever other fields here ...)

Django custom form template

I've a custom template to render my form in my Django website. This code renders the ChoiceFields:
<select id="{{ "id_"|add:field.html_name }}"
class="form-control"
name="{{ field.html_name }}">
{% for id, name in field.field.choices %}
<option value="{{ id }}"
{% if field.value|default_if_none:"" == id %}
selected="selected"
{% endif %}
>{{ name }}</option>
{% endfor %}
</select>
This code works perfectly, when the ChoiceField does not have an initial value. If I sumbit the form, but there's an error in the form (sp I get back to my form, and all the data is in there as I submitted it), the correct choice get the selected="selected" attribute, so it works perfectly fine.
But when I set the default value for the form in my Django view (correctly in the form's init() function, like this: self.fields['card_type'].initial = self.card.card_type_id), this stops working.
If I put manually somewhere in my template the form.value variable it displays the correct integer. In the id, name for-loop there's the same id value. These do not have any whitespace ot something else there. But the code does not works, does not equals to true the self.fields['card_type'].initial = self.card.card_type_id condition.
If I modify the previous code, to print the id, and the field.value instead of the {{name}}, like this: ({{id}}-{{ field.value }}), the following HTML code'll be generated:
<select id="id_card_type" class="form-control" name="card_type">
<option value="3">(3-2)</option>
<option value="2">(2-2)</option>
<option value="1">(1-2)</option>
</select>
There's the id, which is 1, 2, and 3! There's the form.value, which is 2! But there isn't any selected="selected"... Why not working?
Thanks!

Django Select Post Request(return id, not value)

I have code:
<select class="form-control" id="engine" name="engine">
{% for engine in engines %}
<option name="{{engine.id}}">{{engine.name}}</option>
{% endfor %}
</select>
print request.POST:
<QueryDict: {u'engine': [u'test1'], u'csrfmiddlewaretoken': [u'9rICLe2X1m0KBnxLjY7V2gYoeV5Dd3m6']}>
I want get id in "engine"(not value). How I can do it?
Change this line <option name="{{engine.id}}">{{engine.name}}</option> to:
<option value="{{engine.id}}">{{engine.name}}</option>
What do you mean by
I want get id in "engine"(not value)
You mean in your view? Isn't that simply
request.POST['engine']

Categories

Resources