I am working on a project that generates dynamic urls, For ex. if I type 127.0.0.1:8000/newpage it generates a new model with slug newpage
Earlier the project was working fine but suddenly it started to show some bugs.
I am calling a URL using ajax like this (5th line):
$(document).on('click', '#save', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "text:update" %}',
data: {
newText: $('#text-content').val(),
slug: "{{ obj.slug }}",
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
if (json['status'] === 'OK') {
document.getElementById('msg-box').innerText = 'TEXT SAVED';
window.removeEventListener("beforeunload", beforeUnloadListener, { capture: true });
}
},
error: function (xhr, errmsg, err) {
}
});
});
It should load the view which I defined in the update url patterns but because of some reason it is still loading my slug view and generating a new url with slug update, I mean it shouldn't do that if I am telling it to load a specific view in URL pattern then why it is still loading slug view below is my urls.py:
#Only patterns
path('', home, name='home'),
path('<slug:slug>/', textview, name='textview'),
path('update/', update, name='update'),
views.py
def textview(request, slug):
obj, created= Text.objects.get_or_create(slug=slug, defaults={'text':'', 'password':'123'})
return render(request, 'text/textpage.html', {'obj' : obj, 'created' : created})
def update(request):
if request.POST.get('action') == 'post':
slug = request.POST.get('slug')
text = request.POST.get('newText')
obj = Text.objects.get(slug=slug)
obj.text = text
obj.save()
response = JsonResponse({'status':'OK','text':text})
return response
Where are you using this AJAX code? If it is in a JavaScript file (.js), Jinja won't work there, so you have to write the absolute URL or you have to define a variable for the Jinja in the HTML and then use that variable in the JS file.
And try to add a slash after the URL if your APPEND_SLASH not True in settings.py.
Related
I have the following requirement:
Send data to backend using fetch()
receive the data in a view and render another template ( route to a different view)
The following is my code snippet:
JS:
fetch("/addpost", {
method: "POST",
body: JSON.stringify({ value: selecteddict }),
headers: {
"Content-type": "application/json;",
},
})
.then((res) => {
return res.text();
})
.then((text) => {
console.log(text);
});
// the data is being sent successfully
Django View1:
#csrf_exempt
def addpost(request):
if request.method == 'POST':
song = json.loads(request.body.decode('utf-8'))['value']
print(song)
# I want to redirect to another view called createpost that renders a new page
return JsonResponse({'status':201})
return render(request, 'addpost.html')
Django createpost view:
def createpost(request):
return render(request, 'createpost.html')
The view createpost is working fine when given the required path but it is not rendering when it's redirected from addpost
Please suggest a solution to this.
Your addpost view returns as JsonResponse in case of a POST request. If you want to redirect somewhere you need to use redirect() instead of JsonResponse()
My actual page that I want to load takes quite a bit of time because it querying an API for a lot of data (python is doing the backend querying). How can I render my loading page and then render my actual page when the data has been gathered.
What I am trying to do in my view.py
class Page(ListView):
def loading(request):
return render(request,'loading.html')
def viewProfile(request, player_name):
Page.loading(request)
context = {
'data1' : query_api(1),
'data2' : query_api(2),
'data3' : query_api(3),
}
return render(request, 'actualpage.html', context)
In your loading page, make an ajax request to the view which will query the api, and in the success callback set the html data in your template.
However, if the api takes a lot of time, I would suggest you to use celery for processing it asynchronously so that your user can navigate the website normally instead of waiting.
In your template -
$.ajax({
url: "<query_view_url>",
type: "GET",
dataType: 'json',
success: function (data){
$("#div_id").html(data.query_data);
},
error: function(e){
console.log(e);
}
});
In your views.py -
def view_of_query_url(request, <other parameters>):
<query_logic>
data = dict()
data['query_data'] = <your_queried_data> # In html format using render_to_string
return JsonResponse(data)
This is what My ajax call looks like
$.ajax({
url:"{% url 'handsontable' %}",
data: {'getdata': JSON.stringify(hot.getData())},
dataType: 'json',
type: 'POST',
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
This is what my django view looks like.
if request.method == 'POST':
request_getdata = request.POST.get('getdata', 'None')
return HttpResponse(request_getdata)
The alerts in ajax return the data and "success". But my HttpResponse returns "None".
Any idea why it is not passing the data through? Thanks!
First off you are trying to POST to a html file
url:"/utility_tool/decisions/solution_options/handsontable.html",
Instead, it should be a url to a view.
Second, the ajax post request should have the csrftoken in it's header and you can set it up like this:
<script type="text/javascript">
// using jQuery get csrftoken from your HTML
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
// if not safe, set csrftoken
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
url: "{% url 'name of the view from urls.py' %}",
data: {
// here getdata should be a string so that
// in your views.py you can fetch the value using get('getdata')
'getdata': JSON.stringify(hot.getData())
},
dataType: 'json',
success: function (res, status) {
alert(res);
alert(status);
},
error: function (res) {
alert(res.status);
}
});
</script>
And in your django view:
# views.py
from django.http import JsonResponse
def someView(request):
if request.method == 'POST':
# no need to do this
# request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
request_getdata = request.POST.get('getdata', None)
# make sure that you serialise "request_getdata"
return JsonResponse(request_getdata)
And in your urls:
# urls.py
urlpatterns = [
# other urls
path('some/view/', views.someView, name='name of the view in urls.py'),
]
I cannot add comments because I do not yet have up to 50 reputations as demanded by StackOverflow. This is supposed to be a comment under the answer provided by #abybaddi009. He has done a very good job thus far but the answer needs a finishing touch.
In the view
request_getdata = request.POST.get('getdata', None) does not work
but this does
body = request.body.decode('utf-8')
data = body[3]
request.body.decode('utf-8') returns a string which would look something like getdata=your_data you can then use string manipulation techniques or regex to extract your data.
What you need to do is :
code for ajax call ( in js file) to send the data to the view
jQuery.ajax(
{
'url': "url_pattern_in_urls_py_file/",
'type': 'POST',
'contentType': 'application/json; charset=UTF-8',
'data': JSON.stringify({'updated_data':your_data_val}),
'dataType': 'json',
'success': function ( return_data ) {
//success body
}
}
);
code in django view with respect to above POST ajax call to receive the data
import json
if request.method == 'POST':
updatedData=json.loads(request.body.decode('UTF-8'))
I added return false; at the end of the ajax request and it worked. I printed out the values in the view instead of using HttpResponse.
Here's my View,
class ObjLike(RedirectView):
def get_redirect_url(self, *args, **kwargs):
id = self.kwargs.get('id')
obj = get_object_or_404(Data, id=id)
user = self.request.user
if user.is_authenticated():
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
So after this view how can I redirect user to the same page?
I used "return redirect(request.META['HTTP_REFERER'])" but it gives an error "name 'request' is not defined"
I can't use the get absolute URL method, i'm using this view at several places.
So, how can I do that?
to like an object with ajax calls do this
first in html we want to make a like button:
<button id="like">Like!</button>
the add a script that contain the ajax:
<script>
$(document).ready(function() {
$("#like").click(function(event){
$.ajax({
type:"POST",
url:"{% url 'like' Obj.id %}",
success: function(data){
confirm("liked")
}
});
return false;
});
});
</script>
the we add the like url to the urlpatterns list:
url(r'like/obj/(?P<pk>[0-9]+)/', views.like, name="like"),
adding the view :
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def like(request, pk)
obj = Obj.objects.get(id=pk)
obj.likes += 1
obj.save()
return HttpResponse("liked")
Note: you can customize the like view to check if user liked already
When using {% url 'query' %} inside an AJAX get call is returning a string but when I put a static url it works properly.
I'm using Django-Filters and Django-rest-framework in installed apps.
url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^query/$', 'my_app.views.app_function', name='query')
]
app.js
$(document).ready(function(){
// LOAD COOKIE
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function callServer () {
$.ajax({
type: 'GET',
url: "{% url 'query' %}",
success: function (json) {
console.log(json)
},
error: function(x, t, m) {
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
},
headers: {
'X-CSRFToken': csrftoken
}
});
}
$("#query").click(function () {
$('#sub').submit(function (e) {
e.preventDefault();
});
return callServer();
});
});
views.py
class AppFilter(django_filters.FilterSet):
class Meta:
model = Post
fields = ['first', 'second']
#api_view(['GET'])
def app_function(request):
qs = Post.objects.all()
f = AppFilter(request.GET, queryset=qs)
serializer = PostSerializer(f, many=True)
return Response(serializer.data)
forms.py
class QueryForm(forms.Form):
first = forms.TypedChoiceField(
widget=forms.Select,
choices=choice_dict1
)
second = forms.TypedChoiceField(
widget=forms.Select,
choices=choice_dict2
)
Any help before I burn the place?
Django would not be able to resolve {% url 'query' %} in JS file, since that's client side stuff. reverse url is resolved at the time of html file rendering.
What you can do is, pass that url as init() function of that JS module from html file:
<!-- In your Template file -->
<script>
$(function(){
app.init("{% url 'query' %}");
});
</script>
And export the app module from js file. Set that url as a variable, and use it in ajax call.
The problem is that your javascript file (app.js) is probably not the template. You don't show it, but I assume you have an HTML file that is loading the app.js file. The HTML file is where the template variables and such will get expanded. The simplest way to resolve this is to embed the javascript code into your HTML file inside a <script> tag.
There is a library for Flask called Flask-JSGlue that solves this problem and lets you use template variables in your javascript files, but I cannot find a similar library for Django.