How to send data to view without using html forms? - python

I have some data(checkbox and input field) in template file which I want to send to views.Due to page refresh upon submit checkbox field is unchecked.So how to send data to django view without using html form.Is it possible using jquery/ajax?
<form id="myform">
{% csrf_token %}
<p id=id3>Categories</p>
{% for i in My_Cat %}
<input type="checkbox" id="mycheck" name="cat_name" value="{{i.category}}">{{i.category}}<br>
<!--category is db column -->
<!--My_Cat is the context from the view -->
{% endfor %}
<p>Price</p>
₹<input type="text" name="min_price" maxlength="4" size="3" >
to ₹<input type="text" name="max_price" maxlength="4" size="3"><br>
<input type="submit" value="Go" style="margin-top: 6px;">
</form>

It is possible indeed.
Using javascript, catch the form submit event.
In the function, serialize the form (exemple using jquery : https://api.jquery.com/serialize/), or get the field values using selectors.
Craft your ajax request, then send it.
And on view side, don't render a template, use jsonresponse instead : https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects

Related

Failed to get value from html page in Django

I have a problem with trying to get a response from my HTML page using Django (admin).
I have a pretty simple div = contenteditable and need to pass data from this div back after the submit button was clicked.
Everything, including choosing selection and opening the intermediate page works fine. But when I tapped submit button, the condition if "apply" in request.POST failed to work.
Please, tell me, what I'm doing wrong?
This is my Django admin:
class QuestionAdmin(AnnotatesDisplayAdminMixin, admin.ModelAdmin):
def matched_skills(self, question):
return ', '.join(s.name for s in question.skills.all())
def update_skills(self, request, queryset):
if 'apply' in request.POST:
print("something")
skills = []
for question in queryset:
skills.append(self.matched_skills(question))
return render(request,
'admin/order_intermediate.html',
context={'skills': skills})
update_skills.short_description = "Update skills"
This is my order_intermediate.html page:
{% extends "admin/base_site.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
<h1>Adjust skills. </h1>
{% for skill in skills %}
<div>
<div id="title" style="margin-left: 5px" contenteditable="true" > {{ skill }} </div>
</div>
{% endfor %}
<input type="hidden" name="action" value="update_status" />
<input type="submit" name="apply" value="Update skills"/>
</form>
{% endblock %}
Actually, request.POST is an HttpRequest object. For getting available keys in the body of the request, you need to use "request.POST.keys()" method. So, you can simply change your condition to:
if 'apply' in request.POST.keys():
print("something")
In my knowledge, you can not send div content with form submit. However you can use input tag with array in name attribute for this. This will send an array as post variable when submit
First, send skills as a enumerate object from your views
return render(request, 'admin/order_intermediate.html', context={'skills': enumerate(skills)})
Then edit your html to this (Note: if you have css in title id, change it to title class)
{% for i,skill in skills %}
<div>
<input class="title" name="skill[{{ i }}]" value="{{ skill }}" style="margin-left: 5px">
</div>
{% endfor %}
and handle array with any action you want to perform in update_skills()
for skill in request.POST.getlist('skill[]'):
# your code

Django POST dict empty, use simple html form

I am use Django 1.8 and Python 3.5.2, and try recive POST data from simple html form
<form action="/shop/order" method="POST">
{% csrf_token %}
<input type="hidden" name="product-code" value="{{ product.product_code }}">
<input type="text" name="email">
<input type="submit">
</form>
It view where I try get need for me data, but QueryDict empty for POST, when I change POST to GET in form and view all work.
def order_product(request):
test = request.POST.get('product-code', '')
mail = request.POST.get('email', '')
# logger.info(test)
return render(request, 'shop/test.html', dict(test=test, email=mail))
And I'am not understand why is that. Similarly I try parse(decode binary to utf-8 etc) body and I recive empty string.
urls.py
url(r'^order/?$', views.order_product),
Thanks all, the moral of this fable is as follows, use name argument in urls, and use {% url 'name' %} in template. I have i18n in urls(from djangoCMS) and when I harcode url in form isn't work for POST method.

Form post to Django view renders no input to database

So, Im trying to save a todo to a database with django. My template is as follows:
<form action="{% url 'todo:add' %}" method="POST">
{% csrf_token %}
<input type="text" id="text" value="{{new_todo_text}}"/>
<input type="submit" value="Submit todo" />
</form>
{%if not_done_todos %}
<ul>
{%for todo in not_done_todos%}
<li>
<span>{{todo.text}}</span>
</li>
{%endfor%}
</ul>
{%else%}
<span>No todos for you!</span>
{%endif%}
My view where Im trying to catch the "new_todo_text" looks like this:
def add(request):
"""Add todo to database"""
new_todo = Todo(text=request.POST.get('new_todo_text'),
done=False, date_created=timezone.now())
new_todo.save()
return HttpResponseRedirect(reverse('todo:index'))
The problem is that the todo.text turns up empty no matter what I add to the form... whats my problem here?
The problem is that inside your input element you have not declared a name attribute. That name attibute will be used as a key to fetch it with Django request.POST.
So, change to this:
<input type="text" id="text" name="new_todo_text" value="{{new_todo_text}}"/>
The request.POST dict-like will use the input's name and value to build the dict. Then you can do stuff like request.POST['input_name_here'].

Django search as input is entered into form

I currently have a working search form in my project that passes through form data to the GET request. Pretty standard.
What I'm wanting to do is search as data is entered into the search form, so that results will display in real time with search data. This is much like what Google does with the instant desktop results. Is this something that's possible with Django?
Below is my current (simple) search
#views.py
def ProductView(request):
title = 'Products'
all_products = Product.objects.all().order_by("product_Name")
query = request.GET.get("q")
if query:
products = all_products.filter(
Q(product_Name__contains=query) |
Q(manufacturer__contains=query)
).distinct()
return render(request, 'mycollection/details.html', { 'all_products' : products })
-
<!-- HTML -->
<!-- SEARCH BAR -->
<form class="navbar-form navbar-left" role="search" method="get" action="{% url 'mycollection:products' %}">
<div class="form-group">
<input type="text" class="form-control" name="q" value="{{ request.GET.q }}">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
you can save the request.data in to session and if any data is associated with session search data you can put in to value of search box.
request.session['search'] = request.GET.get('q','')
templete :
{% if request.session.search %} {{request.session.search}} {% endif %}

Submit without refresh in django

i have a html form and submit button (It adds or removes relations in manytomanyfield "users"):
{% if user in event.users.all %}
<form action="/event/{{ event.id }}/" method="GET">
<input type="hidden" value="{{ event.id }}" name="remove">
<input type="submit" value="Remove">
</form>
{% else %}
<form action="/event/{{ event.id }}/" method="GET">
<input type="hidden" value="{{ event.id }}" name="add">
<input type="submit" value="Add">
</form>
in views.py:
def show_event(request, event_id):
...
event = get_object_or_404(Event, id=event_id)
user = request.user
if request.GET.get('add'):
event.users.add(user)
event.save()
if request.GET.get('remove'):
event.users.remove(user)
event.save()
return render(request, 'events/event.html', {'event':event, 'user':user,})
This function works fine, but the page refreshes after submitting form. I need no refresh and i need to change button text just like "Follow" button in Twitter. I tried to use some jquery\ajax but i dont exactly understand how it should work. Can please anyone explain how to do it? Thanks.
Here's an extremely basic ajax example. In your form, you can fire your ajax method with:
<a onclick="AjaxFormSubmit()" href="#">Submit</a>
Then your ajax method would be as follows:
function AjaxFormSubmit() {
$.ajax({
url : '/event/{{ event.id }}/',
type : "POST",
data : { the_post : $('#id-of-your-field').val() }
}).done(function(returned_data){
// This is the ajax.done() method, where you can fire events after the ajax method is complete
// For instance, you could hide/display your add/remove button here
});
}
I recommend looking at the Ajax documentation to see all of the Ajax methods available to you.
Also, in your view, you'll need to return (in this example) json data via an HttpResponse. i.e.
return HttpResponse(json.dumps(your_data))
# I like to return success/fail Booleans, personally
*Note, this is untested code.

Categories

Resources