Getting None instead of Value from HTML form (Django) - python

Here below my HTML-template
<form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data">
{% csrf_token %}
<h2>
{{ result }}
</h2>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Show</button>
</div>
</form>
my View.py
def show_result(request):
if request.method == "POST":
result = request.POST.get('test')
return HttpResponse(result)
By pressing the button 'Show' I got None instead of {{ result }} value.
So, how I can get a Value inside curly brackets?
Thanks a lot for any help.

In order to submit the data, they need to be values of form elements like input, textarea, select options...
You can choose the right type for the input field. You can make use of the hidden field type to submit data that will not be displayed to the client...
You probably do not need to use the heading inside the form.
<h2>{{ result }}</h2>
<form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data">
{% csrf_token %}
<div class="d-flex justify-content-center">
<input type="hidden" name="result_field" value="{{ result }}" />
<button type="submit" class="btn btn-primary">Show</button>
</div>
</form>
On the backend, you can retrieve the data as follow:
result = request.POST.get('result_field')
I hope that works for you.

Related

Django multiple radio input from HTML form with same name

I am having a problem with Django forms. I am currently using the request.POST to validate the POST within views.
I want to send inputed-data(radio type) from my template with the same name.
In my template.py:
<form method="post" action="{% url 'app:AnsSubmission' %}">
{% csrf_token %}
{% for i in Exam %}
<div class="form-group col-xl-12">
<label>{{ i.question }}</label>
<div class="radio">
<label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="True" required>True</label>
</div>
<div class="radio">
<label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="False" required>False</label>
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And willing to fetch these data in views.py like:
givenAns_list = request.POST.getlist('givenAns')
for i in givenAns_list:
this_givenAns = givenAns_list[i]
But the problem here is this radio type input field doesn't take value for the same name(not as a list I wish). If I select answer of 2nd question, the 1st one's selection is unselected.
Please suggest how can I fix this?

How to get data from form and show in dropdown in django

What I m trying to do:
Upload a CSV file(Form #1) and show header of a CSV file in the dropdown (Form #2).
and these forms are on the same page.
What I have tried:
for now I able to upload CSV file and display header in a webpage.
index.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="file1">Upload Files</label>
<div class="custom-file">
<input type="file" accept=".csv" id="file1" name="file" required="True" class="form-control custom-file-input">
<label class="custom-file-label" for="file1"></label>
</div>
</div>
<div class="form-group d-flex justify-content-center">
<button type="submit" class="btn text-white w-50" value="Upload">Upload</button>
</div>
</form>
views.py
def read_csv(request):
csv_file = request.FILES['file']
data = pd.read_csv(csv_file)
i = list(data.head(0))
context = {'loaded_data': i}
return render(request, "WebApp/index.html", context)
You can use AJAX request to handle this. You can check this answer, which has a sample AJAX request. In the views.py file, you can handle the request by checking request.is_ajax() and return the context you produce from CSV file via JsonResponse. At the success part of the AJAX call, you can manipulate the dropdown DOM element. There is a good tutorial here. If you are not familiar with these, feel free to ask about the parts you are confused.
So data was in a list I just have to loop through <option>:
<select class="custom-select" id="inputGroupSelect01">
{% for x in loaded_data %}
<option value="{{ x }}">
{{ x }}
</option>
{% endfor %}
</select>

Why request.method is not getting invoked?

I have a read-only textbox which preloaded value from database which upon a button click sends it's value to a method present in backend to perform DELETE query of sql. The problem is occuring when I am click on the button the method is invoked but the request.method condition is not invoked. It is directly going to the end return statement of the method.
#app.route('/home/delete_reminder/<string:id_val>',methods=['GET','POST'])
#is_logged_in
def delete_reminder(id_val):
if request.method=='POST':
desc = request.form['description']
x = desc.split(',')
cur = mysql.connection.cursor()
cur.execute('DELETE FROM set_reminder WHERE DATE=%s,SUBJECT=%s,DESCRIPTION=%s',[x[0],x[1],x[2]])
cur.execute('DELETE FROM recur WHERE RECUR_NEXT=%s',[id_val])
flash('Reminder Deleted','danger')
mysql.connection.commit()
cur.close()
return redirect(url_for('search_reminder_to_delete'))
This is my backend code.
<form method="POST">
{% for data in value %}
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control" readonly="true" value="{{data.DATE}},{{data.SUBJECT}},{{data.DESCRIPTION}}">
</div>
Delete Reminder
{% endfor %}
</form>
This is the html part.
Your button isn't a button, it's a link. You aren't submitting your form.
If you want to fo that then you need to make you form tag:
<form method="POST" action="/home/delete_reminder/{{data.RECUR_NEXT}}">
and switch your button to be a real button that submits the form:
<div class="button">
<button type="submit" class="btn btn-warning">Send your message</button>
</div>
EDIT: Seeing that you want to have multiple possible routes for your form based on the loop.
You could try and use the formaction attribute, although it isn't going to be supported by every browser version.
<form method="POST">
{% for data in value %}
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control" readonly="true" value="{{data.DATE}},{{data.SUBJECT}},{{data.DESCRIPTION}}">
</div>
<div class="button">
<button formaction="/home/delete_reminder/{{data.RECUR_NEXT}}" class="btn btn-warning" type="submit" class="btn btn-warning">Delete Reminder</button>
</div>
{% endfor %}
However this will still result in your description field that is passed to the request having every single description from the whole form in a list or possibly just the last one as a single value (I can't quite remember the behaviour of multiple inputs with the same name), which I don't think is what you're expecting to happen.
It may just be easiest to create a separate form for each link in a loop to be honest:
{% for data in value %}
<form method="POST" action="/home/delete_reminder/{{data.RECUR_NEXT}}">
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control" readonly="true" value="{{data.DATE}},{{data.SUBJECT}},{{data.DESCRIPTION}}">
</div>
<div class="button">
<button class="btn btn-warning" type="submit" class="btn btn-warning">Delete Reminder</button>
</div>
</form>
{% endfor %}

Django template pass array to input field

I have a hidden input field in my django template where I'm passing as value an array.
<form method="post" action="{% url 'flights:flight-selection' %}">{% csrf_token %}
<input type="hidden" id="fa_f_ids" name="fa_f_ids" value="{{ value.fa_f_ids }}">
<button type="submit" class="btn btn-light">Select</button>
</form>
When I submit this form via post request I want to get the value of fa_f_ids as an array but I am getting a string instead when I'd like to get an array.
request.POST.get("fa_flight_id")
#=> <QueryDict: {'csrfmiddlewaretoken': ['UoYqbTUlNxTEJW5AUEfgsgsLuG63dUsvX88DkwGLUJfbnwJdvcfsFhi75yie5uMX'], 'fa_f_ids': ["['AMX401-1560750900-schedule-0000', 'AMX19-1560782100-schedule-0001']"]}>
You need to split the array into several hidden fields, each representing one position of your array:
<form method="post" action="{% url 'flights:flight-selection' %}">
{% csrf_token %}
{% for val in value.fa_f_ids %}
<input type="hidden" name="fa_f_ids[{{ forloop.counter0 }}]" value="{{ val }}">
{% endfor %}
<button type="submit" class="btn btn-light">Select</button>
</form>

Simple django POST not working

I have a form like this:
<form action="{% url "forum.posts" forum=forum.slug thread=thread.slug %}" method="POST">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" placeholder="Začni tipkati.."></textarea>
</div>
<input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>
views.py
'''
Display all posts in a thread or create a new post in a thread.
'''
def posts(request, forum, thread):
forum = Forum.objects.get(slug=forum)
thread = Thread.objects.get(slug=thread)
if request.method == "POST":
return HttpResponse('ok')
posts = thread.posts.all()
return render(request, 'forum/posts.html', {
'forum': forum,
'thread': thread,
'posts': posts
})
urls.py (relevant part):
# List all posts in a thread / Submit a post to a forum
url(r'^(?P<forum>[-\w]+)/(?P<thread>[-\w]+)/$', 'forum.views.posts', name='forum.posts'),
HTML output:
<form action="/forum/o-spletiscu/novatemaa/" method="post">
<input type="hidden" name="csrfmiddlewaretoken" value="4PQWDsAfHyjrhUnYU5P9vVhtaY3vLPBU">
<div class="form-group">
<textarea name="post-body" class="form-control" placeholder="Začni tipkati.."></textarea>
</div>
<input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>
After I hit submit, I expect ok to be returned, instead page refreshes and nothing happens.
Normal GET requests are working though..
What am I missing?
Edit:
It's working when I use #csrf_exempt on posts method.
page refreshes and nothing happens
Problem with your action value. try to inspect it and find wither the url is correct or not.
OR
your form does not have any input with name property.
Try this:
<form action="{% url "forum.posts" forum=forum.slug thread=thread.slug %}" method="POST">
{% csrf_token %}
<div class="form-group">
<textarea class="form-control" placeholder="Začni tipkati.." name="something"></textarea>
</div>
<input type="submit" class="btn btn-success" value="Pošlji odgovor">
</form>

Categories