Saving dropdown menu selection as a cookie in Django - python

I'd like to save a user selection from a dropdown menu as a cookie. I've seen this question asked before but never fully in python.
I wish to use these two cookies in running a simple piece of code so there is no need for a database to be used.
Here is my current HTML code:
<form role="form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="dog-names">Choose a dog name:</label>
<select name="dog-names" id="dog-names" onchange="getSelectValue">
<option value="rigatoni">Rigatoni</option>
<option value="dave">Dave</option>
<option value="pumpernickel">Pumpernickel</option>
<option value="reeses">Reeses</option>
<option value="{{ current_name }}"> {{ current_name }}</option>
</select>
<br/>
<label>Current dog: {{ current_name }}</label>
</div>
<button type="submit" value="Submit" class="btn btn-info">Submit</button>
</form>
Python
def cookies_test(request):
template_name = 'cookies.html'
current_name = "Rigatoni" # default name
if request.method == 'GET':
if 'name' in request.COOKIES:
current_name = request.COOKIES['name']
elif request.method == 'POST':
current_name = request.POST.get('name')
response = render(request, 'test.html', {
"current_name": current_name
})
response.set_cookie('name', current_name)
return response
The python works if I give a value to {{ current_name }}
All I want is to be able to save a value from a dropdown menu in a variable so I can save it as a cookie
Any advice at all would be appreciated :)

Related

get values from html select in views with django

I would like to get the value and even the string if possible of the selected value in my HTML file.
index.html
<form action="#" method="post">
<select id="drop1">
<option disabled selected value> -- select value -- </option>
{% for i in df %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</form>
views.py
def index(request):
if request.method == 'POST':
selected_value = request.POST.get('drop1')
print(selected_value)
else:
return render(request, 'index.html', {'df': df.designation_list})
With this, nothing is returned. I saw that I have to use <form></form> to get an html value but I can't find what to put in the action= field.
Can you see what is missing in my code?
Thanks in advance
The action attribute specifies where to send the form-data when a form is submitted.
In your case, you have to add the url of the view that will hand that data. For example:
<form action="{% url 'index' %}" method="post">
<select id="drop1">
<option disabled selected value> -- select value -- </option>
{% for i in df %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
</select>
</form>
Note: Change the index with the name you specified in your URL pattern.

How to access the selected option in an select tag with Django (not using Javascript)?

I have a form that has a select tag and dynamically created options for that tag as shown below. I want to access the selected tag if it is included in the POST request as part of the form in my Python/Django code:
<form action="{% url 'newprogram' %}" method="post" novalidate>
{% csrf_token %}
TODO: Add Program to School
<select name="schooloptions">
{% for school in schools %}
<option value="{{ school.name }}">{{ school.name }}</option>
{% endfor %}
</select>
<div class="form-group">
<input autofocus class="form-control" type="text" name="programname" placeholder="">
</div>
<input class="btn btn-primary" type="submit" value="Post">
</form>
I want to select the option that the user selects from the drop-down menu as follows but it does not work:
#login_required
def newprogram(request):
if request.method == "POST":
programname = request.POST["programname"]
school = request.POST["schooloptions"].selected() #This does not work and is what I need help with
schoolobj = School.objects.get("school")
school = Program(School=schoolobj, name=programname)
school.save()
return render(request, "network/index.html")
Any thoughts as to how I can access the selected option from a select HTML tag within a form?

Rendering a FormSet in Django

I want to create a FormSet which allows users to add forms as needed. However, when I render the page, I am receiving an error:
ValueError: The view website.views.presales didn't return an HttpResponse object.
It returned None instead.
I would like to always render the form blank. Please let me know if any other information is needed, thanks!
Note: cwObj.get_opportunities() is an API call to create an object from a JSON response to populate the select_opportunity dropdown. Lastly, I am using AJAX to dynamically calculate the value of the span Total using data-total-url="{% url 'presales_total' %}".
forms.py
class PresalesForm(forms.Form):
class Meta:
model = Presales
fields = ('selected_opportunity', 'task_description', 'hours', 'selected_engineer_level', 'total_cost')
views.py
def presales(request):
my_opportunities = cwObj.get_opportunities()
PresalesFormSet = formset_factory(PresalesForm, extra=1)
if request.method == 'POST':
presales_formset = PresalesFormSet(request.POST)
if presales_formset.is_valid():
for presales_form in presales_formset:
selected_opportunity = request.POST.get('selected_opportunity')
task_description = request.POST.get('task_description')
hours = request.POST.get('hours')
select_engineer_level = request.POST.get('select_engineer_level')
else:
presales_formset = PresalesFormSet(initial="None")
context = {'presales_formset': presales_formset, 'my_opportunities': my_opportunities}
return render(request, 'website/presales.html', context)
presales.html
<form action="{% url 'presales' %}" method="post" name="presalesForm" id="presalesForm" data-total-url="{% url 'presales_total' %}">
{% csrf_token %}
{{ presales_formset.management_form }}
{% for presales_form in presales_formset %}
<div class="field">
<label class="label is-large">Create Task</label>
</div>
<div class="section">
<div class="field">
<label class="label">Opportunity</label>
<div class="select">
<select name="select_opportunity" id="select_opportunity">
<option value="">Opportunity</option>
{% for opportunity in my_opportunities %}
<option name="selected_opportunity" id="selected_opportunity" value="{{ opportunity.name }}">{{ opportunity.name }}</option>
{% endfor %}
</select>
</div>
</div>
<label class="label">Task Description:</label>
<div class="field">
<div class="control">
<input class="input" name="task_description" id="task_description" placeholder="Task Description">
</div>
</div>
<label class="label">Hours</label>
<div class="field">
<div class="control">
<input class="input" name="hours" id="hours" placeholder="Hours">
</div>
</div>
<label class="label">Engineer Level:</label>
<div class="field">
<div class="select">
<select name="select_engineer_level" id="select_engineer_level">
<option value="">Engineer Level</option>
<option value="PM">PM</option>
<option value="Solutions Technician">Solutions Technician</option>
<option value="Solutions Engineer">Solutions Engineer</option>
<option value="Senior Solutions Engineer">Senior Solutions Engineer</option>
<option value="Solutions Architect">Solutions Architect</option>
</select>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-info" type="button">Add Task</button>
</div>
</div>
{% endfor %}
<span class="label is-medium is-pulled-right" id="total_cost">Total: {{ total }}</span>
</form>
Your view does NOT return an HttpResponse in all cases, which is an error. This happend when request.method is different than POST and when the formset is not valid.
This is pretty easy to spot when removing most of the code and just leaving the conditional statements:
def presales(request):
if request.method == 'POST':
if presales_formset.is_valid():
...
return render(request, 'website/presales.html', context)
You have to return other HttpResponse's in the other cases as well to solve this error.
For example, you could un-indent the line return render(... 2 levels, so that the view always returns the template.

Can't get form data in view function: Django

I need to submit a string to a view function via a dropdown menu and submit button.
in my template I have:
<form action="{% url 'exec_task' %}" method="post">
{% csrf_token %}
<select id="select_task" form="select_task" name="select_task">
{% for task in available_tasks %}
<option id="selected_task" value="{{ task }}">{{ task }}</option>
{% endfor %}
</select>
<input class="button" type="submit" value="Run Selected Task">
</form>
in my view function I have:
def exec_task(request):
if request.method == 'POST':
task = request.POST.get('select_task')
print(task)
getattr(tasks, task)(0)
return redirect('management')
The print(task) always comes out as None, which generates an error when I try to call it via getattr in the next line.
I've read through all the questions and tutorials I can find on this and I don't know what I'm doing wrong, but when I print the request.POST object, all I get is the csrf token. The QueryDict has nothing else in it.
Any ideas?
As discussed in comments please remove
form="select_task" from select tag.
So final select tag / html would be.
<form action="{% url 'exec_task' %}" method="post">
{% csrf_token %}
<select id="select_task" name="select_task">
{% for task in available_tasks %}
<option id="selected_task" value="{{ task }}">{{ task }}</option>
{% endfor %}
</select>
<input class="button" type="submit" value="Run Selected Task">
</form>

Displaying results on the same page with Flask

I am trying to write code that will request data for a page, process it, and then show the result in a lower section of the page without refreshing.
Flask code:
if request.method == 'GET':
return render_template("dashboard.html", data_nodes=data_nodes, data_para=data_para)
elif request.method=='POST':
#c, conn = connection2()
select1 = request.form.get('node')
select2 = request.form.get('parameter')
print str(select1)
print str(select2)
#processes the data
#display the processed data on the same page
#return render_template("dashboard.html") This will refresh the page! Is there another way?
My HTML side
<form method="POST" action="{{ url_for('dashboard')}}">
<label for="node">Node</label>
<select name="node">
{% for o in data_nodes %}
<option value="{{ o.name }}">{{ o.name }}</option>
{% endfor %}
</select>
<label for="parameter">Parameter</label>
<select name="parameter">
{% for o in data_para %}
<option value="{{ o.name }}">{{ o.name }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-default" >Send</button>
</form>
Is there a way to post the processed data without having to redirect to another page?

Categories

Resources