Django with request in ajax - ajax

This is my request in ajax,
var req=$.ajax({
type: "POST",
url: '/create/travel', // or just url: "/my-url/path/"
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
startPlace:nameStart,
startLng:lngStart,
startLat:latStart,
endPlace:nameEnd,
...
}
});
Then, it is my view
def createT(request):
if request.is_ajax():
#print(request.POST['board'])
print(Car.objects.get(number_plate=request.POST['number_plate']))
travel1=Travel.objects.create(
name=request.POST['name_travel'],
startPlace=request.POST['startPlace'],
...
)
return render_to_response('travel/meTravel.html',{},context_instance=RequestContext(request))
But django not go to the template, i dont know how i go to other view or open other page, other template,
Simply when i come to this view, i cannot open other view, single django stay in the same page. =$
Help me! Tanks ,

finally, I make a form and send the normal request, Tanks for all...
class TravelForm(ModelForm):
class Meta:
model = Travel
exclude=("responsible",)
widgets = {
'date': DateTimeWidget (attrs={'id':"date"},use_tz=True,bootstrap_version=3)
}
def __init__(self, user, *args, **kwargs):
super(TravelForm, self).__init__(*args, **kwargs)
self.fields['number_plate'].queryset = Car.objects.filter(proprietor=user)
and my view
def TravelCreate(request):
if request.method == "POST":
form = TravelForm(request.user.id, request.POST)
print("POST HERE-----------------=)")
print(form.is_valid())
if form.is_valid():
obj=form.save(commit=False)
obj.responsible = request.user
obj.save()
return HttpResponseRedirect('/TravelsMe')
else:
form = TravelForm(request.user.id)
return render_to_response('travel/travel_form.html', {'form':form}, context_instance=RequestContext(request))
And some code of ajax,

Related

How to Notify User that Asynchronous Task is Completed?

I am using threading library for a long-running process in Django. When the process is completed, I want to keep updating progress status on the front-end. I am unable to post anything to the ajax.get() from my thread function.
View.py
def upload_handler(request, file_loc, filename):
// do something with uploaded
// I want to notify user that this process is complete via a post
class Uploader(View):
def get(self, request):
file=UploadForm()
return render(request,'template.html',{'form':file}) #,'files':files})
def post(self, request):
file = UploadForm(data=request.POST, files=request.FILES)
if file.is_valid():
x = request.FILES['file']
file.save()
filename = str(request.FILES['file'])
file_loc = os.path.join(BASE_DIR, 'media', 'images', filename)
upload_thread = Thread(target=upload_handler, args=(request, file_loc, filename))
upload_thread.start()
return HttpResponseRedirect(reverse('imageupload'))
urls.py
urlpatterns = [
path('', Uploader.as_view(), name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
ajax call script
{
$.ajax({
type:"get",
url:"/uploader",
datatype:"json",
success:function(data)
{
console.log(data);
alert("Your file is processed now!");
}
});
}, 1000);
Assume that file uploaded page will remain open till the long process completes.
AJAX option datatype is "json", but the View does not return a "json".

Multiple ajax requests kill django server

I have a single view which scrolls through user data. There are next and previous buttons to scroll. When user presses next, ajax sends the user id to the django view and displays the data.
If user clicks the next button two or three times consecutively (which they usually do), the calls get aborted and server is killed.
$("#new").click(function() {
$.ajax({
type:'POST',
url:'/new/',
data:{
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:searchSuccess,
dataType: 'html'
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#myForm').html(data);
}
This is the view.
def master_detail_next(request):
def decrement_voucher_id(form_id):
voucher_id = str(int(form_id) - 1).zfill(4)
return voucher_id
if request.method == 'POST':
form_id = request.POST['voucher_id']
voucher_id = decrement_voucher_id(form_id)
voucher_id = get_decremented_voucher_id(voucher_id)
else:
voucher_id = ''
# Inline forms
author = TmpPlInvoice.objects.get(voucher_id=voucher_id)
author_form = TmpForm(instance=author)
BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet,
exclude=('emp_id', 'voucher', 'lineitem', 'id',),
form=TmpFormDetForm, )
formset = BookFormSet(instance=author)
totalform = TmpFormTotal(instance=author)
postform = CheckPostedForm(instance=author, posted=author.posted)
return render(request, 'form.html', {'form': author_form, 'formset': formset, 'formtotal': totalform, 'postform': postform})
How can i avoid that? What is that i am doing wrong?

Django, Ajax- HttpResponse does not send json

Django 1.7.2/ python 3.4
this code is about 'like'.
if user click the 'like' button, ajax calls 'pushLike'.
if the user has liked the article before(saved inside Mysql), delete the row on table(DB).
or if the user is not liking the article, create a row and insert it on the table(DB).
after that, count how many like has beed clicked on that article.
I would like to pass the likeCnt(count) to ajax, and write it on the button.
The likeCnt has the right value(I checked it on the server mysql table).
The button color does change(white to blue, and vise versa), but the text does not change.
It seems like json does not pass to ajax. I tried passing data by 'text' type and it did worked, but i want it by json.
I've tried simplejson, json, mimetype, content_type on HttpResponse.
please help me.
view
#login_required
def pushLike(request):
pk = request.GET['writing_id']
try:
la = LikeArticles.objects.get(user = User.objects.get(username=request.user.username), article_id=pk)
if(la.is_like()):
la.delete()
likeCnt = LikeArticles.objects.filter(article_id=pk).count()
FreeBoards.objects.filter(id=pk).update(like = likeCnt)
else: #Never happens
la.like = True
la.save()
likeCnt = LikeArticles.objects.filter(article_id=pk).count()
FreeBoards.objects.filter(id=pk).update(like = likeCnt)
except ObjectDoesNotExist:
la = LikeArticles(user = User.objects.get(username=request.user.username),
article = FreeBoards.objects.get(id=pk),
like = True,
)
la.save()
likeCnt = LikeArticles.objects.filter(article_id=pk).count()
FreeBoards.objects.filter(id=pk).update(like = likeCnt)
data = {'likeCnt': likeCnt}
# return render(request, url, context)
return HttpResponse(simplejson.dumps(data), mimetype='application/javascript')
javascript
<script type="text/javascript">
$(document).ready(function(){
$('#btn-like').click(function(){
var e = $('#btn-like').css('background-color');
$.ajax({
url : '/sle/freeboards/pushLike/',
data : {'writing_id':{{writing_id}},
},
dataType : "json",
success:function(data){
alert(data.likeCnt);
if(e == 'rgb(59, 89, 152)') {
$('#btn-like').css('background-color', '#ffffff').css('color', '#000000');
$('#btn-like').text(data.likeCnt);
} else {
$('#btn-like').css('background-color', '#3b5998').css('color', '#ffffff');
$('#btn-like').text(data.likeCnt);
}
},
failure: function(data){
alert('fail!!')
}
});
});
});
</script>
you'll want to be sure to set the proper mimetype in your HttpResponse
#login_required
def pushLike(request):
...
# return json -- !!not javascript!!
return HttpResponse(simplejson.dumps(...), mimetype="application/json")
--or--
#login_required
def pushLike(request):
...
# return json -- !!not javascript!!
return JsonResponse({"your": "context dictionary"})
If that doesn't work, have you tried parsing the json with your Jquery code?
ie:
$.ajax({
...
success: function(data){
var response = $.parseJSON(data);
...
}
});
javascript might actually receiving bytes back from whatever you are serving your django app with... so instead of getting JSON back, you're actually getting string that looks like JSON. http://api.jquery.com/jquery.parsejson/

render a view to the client with json request

I come back with this with new question and more clear description, I hope, because I made a lot of changes but i havent found a working solution yet. To start from the beginning I have a view which whenever I push a button I want to return the rendered view from another view.
#csrf_exempt
def main(request):
menu_beer = Food.objects.filter(category=4)
menu_crepe = Food.objects.filter(category=2)
menu_club = Food.objects.filter(category=1)
menu_spaggetti = Food.objects.filter(category=8)
menu_burgers = Food.objects.filter(category=11)
menu_hotdog = Food.objects.filter(category=1)
menu_salads = Food.objects.filter(category=7)
menu_toast = Food.objects.filter(category=3)
menu_dessert = Food.objects.filter(category=6)
menu_coffee = Food.objects.filter(category=9)
menu_soda = Food.objects.filter(category=5)
menu_food = Food.objects.filter(category=1)
menu_offer = Offer.objects.all()
obj={}
print "request ajax------------------------"
if request.is_ajax():
print "inside ajax\/\/\//\/\/\/"
sItem=request.GET.get('itemId')
print "GET itemId="+sItem
if sItem is not None:
getobject=Food.objects.get(id=int(sItem))
print getobject
obj['id']=getobject.id
obj['title']=getobject.title
print "{}= "+str(obj)
return HttpResponse(json.dumps(obj), content_type="application/json")
else:
print "ERRRRRRR"
return render(request,'main.html',{'view_title':"Menu",
'menu_crepe':menu_crepe,
'menu_club':menu_club,
'menu_spaghetti':menu_spaggetti,
'menu_burgers':menu_burgers,
'menu_hotdog':menu_hotdog,
'menu_salads':menu_salads,
'menu_toast':menu_toast,
'menu_dessert':menu_dessert,
'menu_coffee':menu_coffee,
'menu_soda':menu_soda,
'menu_beer':menu_beer,
'menu_offer':menu_offer,
})
def profile(request):
return render(request,'profile.html')
#csrf_exempt
def order(request):
obj={}
print "request ajax------------------------"
if request.GET:
print "POST"
sItem=request.GET.get('itemId')
print "GET2 itemId="+sItem
if sItem is not None:
getobject=Food.objects.get(id=int(sItem))
print getobject
obj['id']=getobject.id
obj['title']=getobject.title
print "post2= "+str(obj)
return render(request,'order.html',{"obj":obj})
else:
print "ER"
return render_to_response("order.html",{'obj':obj})
js is like:
$(document).ready( function(){
$(".orderbtn").click(function(){
p=$(this).prop("id");
$.ajax({
type:"GET",
url:"order/",
data:{"itemId":p
//'csrfmiddlewaretoken': $("{% csrf_token %}")
},
success: function(data){
$('#selected').html("data.title");
}
});
});
});
All the code and the files are https://github.com/b10n1k/foodspot69.git
and the part of main.html where should display the data between div with id="menu_display".
<div id="selected" class="selected"></div >
So, I am not sure how must handle each view in this case. Any suggestion what I am doing wrong?
I found the solution on this and I post it without details to help others. In success function I added two parameters and now it looks:
success: function(data){
$('#selected').html(data, textStatus, jqXHR);
}
I hope someone can give more details about because I dont know why they are required.

Ajax Authentication with Tastypie Django

I followed this to create my ajax authentication. The ajax does not send the POST data; it sends an empty querydict. If I explicitly write my username and password in my ajax view, it logins in and out perfectly... but that is useless.
I found the answer. This has been updated for Django 1.5.1. The code below works.
#Ajax_Views.py
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpRequest
from django.conf.urls import url
from django.utils import simplejson
from tastypie.http import HttpUnauthorized, HttpForbidden
from tastypie.utils import trailing_slash
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['first_name', 'last_name', 'email']
allowed_methods = ['get', 'post']
resource_name = 'user'
authorization = Authorization()
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/login%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('login'), name="api_login"),
url(r'^(?P<resource_name>%s)/logout%s$' %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('logout'), name='api_logout'),
]
def login(self, request, **kwargs):
self.method_check(request, allowed=['post', 'ajax'])
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )
def logout(self, request, **kwargs):
self.method_check(request, allowed=['get'])
if request.user and request.user.is_authenticated():
logout(request)
return self.create_response(request, { 'success': True })
else:
return self.create_response(request, { 'success': False }, HttpUnauthorized)
#Jquery/Ajax
$('#send').click(function(e){
e.preventDefault();
data = {
"username": $('#username').val(),
"password": $('#password').val()
};
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000/api/user/login/",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function(data) {console.log(data)},
error: function (rs, e) {console.debug(rs)}
});
});
#The HTML
<input type='text' id='username' />
<input type='password' id='password'/>
<input type='submit' id='send' class='btn' href='#'>Send</a>
I'm trying to build out a front end in Backbone for a Django 1.5 app.
I understand the Tastypie stuff and have been able to get that working, but I'm not sure how the page knows if the user is logged in or not when the page is first visited. I am using Session storage - is this incompatible with a JavaScript front end? Do I need to manually store the CSRF token and delete it after the user logs in, am I forced to use Django's (non-Ajax) for login/logout and then redirect to a protected, django served page with the JavaScript app code?
I am serving the JavaScript from django now, to get the CSRF token.. So I think I'm on the right path.

Resources