Django star rating system and AJAX - python

I am trying to implement a star rating system on a Django site.
Storing the ratings in my models is sorted, as is displaying the score on the page. But I want the user's to be able to rate a page (from 1 to 5 essentially) without a refresh or change of page.
I have found the following, and like the style of the stars here: http://jvance.com/blog/2008/09/22/JQueryRaterPluginNew.xhtml
Currently have a limited understanding of javascript and AJAX. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating?
It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. It is stored in the models whether they have already voted and what their previous vote was. But how would I be able to modify the stars to show this?
So if you know how to do these things, or a more appropriate star rating graphics solution, or any good tutorials... please do share. Thank you.

AJAX sounds scary and confusing but it doesn't have to be. Essentially what you want to do is post some data to a particular url/view combo. See jQuery.post for more information on using AJAX to send data to the server.
#urls
urlpatterns += patterns('',
url(r'^article/rate/', 'article.rate'),
#views
def rate(request):
if request.method == 'POST':
# use post data to complete the rating..
#javascript
$.post("/article/rate", { rating: 3, article: 2 },
function(data) {
// success! so now set the UI star to 3
});
As far as I know, star-ratings are produced with radio controls and css. So if you want to show the current rating per user on load of the page, just have your template render the associated radio with the checked option.

Jonathan you are welcome to the django world. as Django is a cool framework some djangonauts have written nice sites to help us.
if you go to http://djangopackages.com/categories/apps/ and search "rating" you will find some django pluggables with examples that will help you a lot with your project.
also see those util answers in another question: Best Practices: How to best implement Rating-Stars in Django Templates

Working on this recently, so thought I would provide a solution to the mix. Firstly, I'm using RateIt, which I have found to be very simple to set up and quite intuitve to use (add the RateIt *.js and .*css files to your base.html template):
http://www.radioactivethinking.com/rateit/example/example.htm
Here are the key pieces to my solution:
urls.py
url(r'^object/rate/$', RateMyObjectView.as_view(), name='rate_my_object_view'),
my_template.html
<div class="rateit" data-rateit-resetable="false">Rate it!</div>
ajax.js
$('.rateit').bind('click', function(e) {
e.preventDefault();
var ri = $(this);
var value = ri.rateit('value');
var object_id = ri.data('object_id');
$.ajax({
url: '/object/rate/?xhr',
data: {
object_id: object_id,
value: value
},
type: 'post',
success: function(data, response) {
console.log("ajax call succeeded!");
},
error: function(data, response) {
console.log("ajax call failed!");
}
});
});
Some view bits are from James Bennett (setting xhr, for example):
http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/
views.py
from django.views.generic.base import View
from .models import MyObject
class RateMyObjectView(View):
def post(self, request):
my_object = MyObject.objects.all().last()
xhr = 'xhr' in request.GET
star_value = request.POST.get('value', '')
my_object.score = star_value
my_object.save()
response_data = {
'message': 'value of star rating:',
'value': star_value
}
if xhr and star_value:
response_data.update({'success': True})
else:
response_data.update({'success': False})
if xhr:
return HttpResponse(json.dumps(response_data), content_type="application/json")
return render_to_response(self.template_name, response_data)
models.py
from django.db import models
class MyObject(models.Model)
score = models.FloatField(max_length=1, default=0)
Keep in mind that this is a naive solution, and simply replaces the current star score in the last item in your object list. It's not ideal, as it would be better to store scores as their own model and link to the object. This was you can store them and do calculations like average, etc. I'm working on this now and will update this answer when I'm finished.

Related

AJAX request returns HTML file instead of data. ( Django & Python )

I have a profile page with user posts. People can like/dislike the posts. It works well but it reloads the page, that is why I am implementing AJAX.
The route goes like this.
Inside the profile view is the "like POST" request ending with a
data = {
'likes':post.likes.all().count()
}
return JsonResponse(data,safe=False)"
When clicking on the like button, I can see the data on a blank page if I want to. So I know it is receiving it.
Unfortunately, when using AJAX, instead of returning the data. it returns the profile view's
return render(request, "profile.html", context)
Here is my AJAX code
const post_id = $(this).attr('id')
const likeText = $( `.like_button${post_id} `).attr('name')
const trim = $.trim(likeText)
const url = $(this).attr('action')
let res;
const likes = $(`.like_count${post_id}`).text() || 0
const trimCount = parseInt(likes)
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(),
'post_id':post_id,
},
success: function(data){
console.log('success', data)
},
error: function(data){
console.log('error', data)
}
})
Any help would be much appreciated. First time using AJAX, so as much details would be appreciated.
Not really surprising it's returning HTML since that's exactly what you're returning in the view: rendered HTML. If you want JSON you need then you want a JSONResponse object.
https://docs.djangoproject.com/en/4.1/ref/request-response/#jsonresponse-objects
So, instead of:
return render(request, "profile.html", context)
which will take the profile.html, inject the values from context and send you that as html, you should do something like:
response = JsonResponse({"mydata": "goes here", "some_more": data})
You can then parse this as JSON in your AJAX code. If it's the case that the context dictionary contains all the data you need and that is what you want, you can just swap out that one line:
response = JsonResponse(context)
Edit: To address the question in the comment. Suppressing the default form response in the frontend is not a Django thing, it's done with JS on the event using something like:
e.preventDefault()
See here for info: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

How to add a object to a users watch list via a link in Django

I have a website that recommends anime and I want each anime to have some text besides them as they appear, offering to add to a users 'list' which is a page where all anime in the users account-unique list will be shown. I have it working, and can add via the django admin but not via a button on the website.
models.py
class UserList(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
anime_in_list = models.ManyToManyField(Anime, blank=True)
views.py
#login_required
def userList(request):
return render(request, 'userlist.html')
def add_to_userlist(request, anime_id):
new_anime = get_object_or_404(Anime, pk=anime_id)
#if UserList.objects.filter(user=request.user, anime_in_list=anime_id).exists():
#message fail
user_list, created = UserList.objects.get_or_create(user=request.user)
user_list.anime_in_list.add(new_anime)
return render(request, "userlist.html")
on the html where the anime shows
Add to list?
urls.py
urlpatterns = [
...
path('userlist/', user_views.userList, name='userlist'),
path('anime/', AnimeListView.as_view(), name='all-anime'),
...
]
but navigating to the anime html page now the error NoReverseMatch at /anime/
Reverse for 'add_to_userlist' not found. 'add_to_userlist' is not a valid view function or pattern name.
But I don't want to create a separate url to redirect them, I just want pressing the to add to the users list, and if the user now navigates to their /userlist, they find that it has updated with the anime they clicked the link on.
Essentially it could be thought of like a shopping cart, where products exist and I just want to be able to click on them to add them to my list that works with the way I have models.py.
Any help would be super appreciated, ty
I am not an expert, but you can try to return an empty HttpResponse
from django.http import HttpResponse
return HttpResponse('')
and on client side do a AJAX call to that view.
Look Here
or even better return a json which has included information about the proccess was succesfully or not and handle that result correctly on js side.
from django.http import JsonResponse
return JsonResponse({'status':'Anime already added'})
Needs JQuery
$.getJSON( "<django view url>", function(data) {
console.log( "success" );
}).done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});

Django filtering queryset

Here is my simple view:
def transaction_list(request):
current_user = request.user
month = datetime.date.today().month
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
objects = Transaction.objects.filter(user=current_user, date__month=month)
p = Paginator(objects, 10, request=request)
transactions = p.page(page)
return render(request, 'transaction/list.html',
{'transactions': transactions})
It shows a list of transactions which occured in the current month.
I want to add an option to change the month of the transactions being displayed but I have no clue how to tackle this and make it work. Should it be done in a view? maybe template? I would appreciate any ideas
Take some time to read some Django docs as they may prove really valuable (not to mention they are very clean and well written for every version available). I would focus on Working With Forms
In short, you'll pass the month from your django template (maybe via ajax or a simple HTML form POST), to your view, and use your view function to get the POST data and use that in your queryset.
It is hard to provide a good, thorough answer because there are different ways to do this. Do you want AJAX? Simple form with page reload, etc? 
Okay, here, in detail, is how I usually handle a POST request. This isn't tested code, it's just psuedo code, but should work as far as I can tell, aside from a few minor typos probably. BUT, it should give you an idea of how to handle ajax requests in Django.
This is pretty 101 and taking some time to read the docs and run through some of the early projects covers a these concepts much I, so my going into more depth isn't really valuable to SO readers.
views.py
class change_date_form(forms.Form):
new_date = forms.DateField()
def change_transaction_date(request):
#Do some checks to make sure user is authorized to do this
current_user = ...
customer_data = []
if request.method == 'POST':
form = change_date_form(request.POST, request.FILES)
if form.is_valid():
change_date = form.cleaned_data.get('new_date')
objects = Transaction.objects.filter(user=current_user, date__month=change_date)
for i in objects:
customer_data.append(objects.name)
response_data = json.dumps(customer_data)
return HttpResponse(response_data, content_type='application/json')
urls.py
...
url(r'^change_date_view/', 'module.views.change_transaction_date'),
Jquery:
$('button_handler').on('click', function() {
var new_date_value = $(date_field_selector).val()
$.ajax({
url: "/change_date_view/",
type: "POST",
data: {
new_date: button_handler,
},
success:function(data) {
//build your html via javascript with response data
}
})
})

url patterns for home views or using views accross apps

I've been reading about urls, but I can't seem to find a analogue to what I'm trying to do. I have an app called profile, the views.py in this app queries the database and returns user specific content - I use filters to summarize the db content to whatever user is logged in. In my "home page" I would like to have a summary of the database across all users.
so the urls used in the profile app looks like this:
url(r'^profile/$', 'profile.views.profile', name='profile'),
url(r'^profile/usrDash$', 'profile.views.usrDash')
the first one renders the "profile page" and the second is used by an ajax call to send some user specific info which in turn is used to formulate the query. That's working fine; no issue there.
so what if I wanted to display the same information, use the same query, on the "home page" too? How do I do that? Not exactly what I want to do, but If I can this to work I can adapt it later. I've tried:
url(r'^home/usrDash$', 'profile.views.usrDash')
but ajax doesn't seem to like it. there are no error messages it just doesn't POST anything.
I've also tried writing another view in home.views.py, but I can't seem to get the url right. Since the url pattern for "home page" is:
url(r'^$', 'home.views.home', name='home')
wouldn't the url for a query at home.views.py be:
url(r'^/usrDash$', 'home.views.usrDash')
The ajax call in question looks like this:
$.ajax({
method: "POST",
url: "profile/usrDash",
dataType: "json",
data: {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
someVariable: someVariable,
},
success: function(Data) {
...
...
},
error: function() {
...
}
});
So the ajax call from "home" is a copy of the ajax call used in "profile" with the modification of adding the profile/. But that doesn't work either.
Thanks in advance for your help.
Regards.
It looks like you have two apps, one called "profile" and another called "home". If I understand correctly, you would to like make an ajax post request processed by "profile.views.usrDash" to get information for the home page.
So, why not just make the ajax request to '/profile/usrDash'? Why are you associating a different URL pattern with the usrDash view?
The code you provided which attempts to reuse the usrDash view has an incorrect path. It should be profile.views.usrDash
Turns out that there were two issues with my code. The first was the way the csrf token was being passed to ajax. In my profile app this works:
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
But it doesn't work in home app. I don't know why. It works in one app and not the other. What did work is:
csrfmiddlewaretoken: '{{ csrf_token }}',
I found this answer on this post:
csrf token issue with multiple templates
The second issue was the url, which was easy to diagnose once the csrf token issue was resolved. the final url is simply:
url(r'^usrDash$', 'profile.views.usrDash')
No need for the leading /.
Thanks to ArbyA for taking time to look through my code and thanks to doniyor whose response to the post linked above helped finally get this working.
Regards.

How do I integrate Ajax with Django applications?

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together.
Could someone give me a quick explanation of how the codebase must change with the two of them integrating together?
For example, can I still use the HttpResponse with Ajax, or do my responses have to change with the use of Ajax? If so, could you please provide an example of how the responses to the requests must change? If it makes any difference, the data I am returning is JSON.
Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).
Django is server-side. It means, say a client goes to a URL, you have a function inside views that renders what he sees and returns a response in HTML. Let's break it up into examples:
views.py:
def hello(request):
return HttpResponse('Hello World!')
def home(request):
return render_to_response('index.html', {'variable': 'world'})
index.html:
<h1>Hello {{ variable }}, welcome to my awesome site</h1>
urls.py:
url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),
That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello means a request to the hello() function, going to 127.0.0.1:8000/home will return the index.html and replace all the variables as asked (you probably know all this by now).
Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.
For example, an AJAX call to 127.0.0.1:8000/hello will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you'd like. Let's look at a simple use case:
$.ajax({
url: '127.0.0.1:8000/hello',
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});
The general process is this:
The call goes to the URL 127.0.0.1:8000/hello as if you opened a new tab and did it yourself.
If it succeeds (status code 200), do the function for success, which will alert the data received.
If fails, do a different function.
Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an AJAX call to home? Same thing, you'll get an alert stating <h1>Hello world, welcome to my awesome site</h1>.
In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:
Learn jQuery. I cannot stress this enough. You're gonna have to understand it a little to know how to handle the data you receive. You'll also need to understand some basic JavaScript syntax (not far from python, you'll get used to it). I strongly recommend Envato's video tutorials for jQuery, they are great and will put you on the right path.
When to use JSON?. You're going to see a lot of examples where the data sent by the Django views is in JSON. I didn't go into detail on that, because it isn't important how to do it (there are plenty of explanations abound) and a lot more important when. And the answer to that is - JSON data is serialized data. That is, data you can manipulate. Like I mentioned, an AJAX call will fetch the response as if the user did it himself. Now say you don't want to mess with all the html, and instead want to send data (a list of objects perhaps). JSON is good for this, because it sends it as an object (JSON data looks like a python dictionary), and then you can iterate over it or do something else that removes the need to sift through useless html.
Add it last. When you build a web app and want to implement AJAX - do yourself a favor. First, build the entire app completely devoid of any AJAX. See that everything is working. Then, and only then, start writing the AJAX calls. That's a good process that helps you learn a lot as well.
Use chrome's developer tools. Since AJAX calls are done in the background it's sometimes very hard to debug them. You should use the chrome developer tools (or similar tools such as firebug) and console.log things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.
CSRF awareness. Finally, remember that post requests in Django require the csrf_token. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.
That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.
Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses AjaxableResponseMixin and assumes an Author model.
import json
from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return self.render_to_json_response(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return self.render_to_json_response(data)
else:
return response
class AuthorCreate(AjaxableResponseMixin, CreateView):
model = Author
fields = ['name']
Source: Django documentation, Form handling with class-based views
The link to version 1.6 of Django is no longer available updated to version 1.11
I am writing this because the accepted answer is pretty old, it needs a refresher.
So this is how I would integrate Ajax with Django in 2019 :) And lets take a real example of when we would need Ajax :-
Lets say I have a model with registered usernames and with the help of Ajax I wanna know if a given username exists.
html:
<p id="response_msg"></p>
<form id="username_exists_form" method='GET'>
Name: <input type="username" name="username" />
<button type='submit'> Check </button>
</form>
ajax:
$('#username_exists_form').on('submit',function(e){
e.preventDefault();
var username = $(this).find('input').val();
$.get('/exists/',
{'username': username},
function(response){ $('#response_msg').text(response.msg); }
);
});
urls.py:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('exists/', views.username_exists, name='exists'),
]
views.py:
def username_exists(request):
data = {'msg':''}
if request.method == 'GET':
username = request.GET.get('username').lower()
exists = Usernames.objects.filter(name=username).exists()
data['msg'] = username
data['msg'] += ' already exists.' if exists else ' does not exists.'
return JsonResponse(data)
Also render_to_response which is deprecated and has been replaced by render and from Django 1.7 onwards instead of HttpResponse we use JsonResponse for ajax response. Because it comes with a JSON encoder, so you don’t need to serialize the data before returning the response object but HttpResponse is not deprecated.
Simple and Nice. You don't have to change your views. Bjax handles all your links. Check this out:
Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here:
Bjax Demo
AJAX is the best way to do asynchronous tasks. Making asynchronous calls is something common in use in any website building. We will take a short example to learn how we can implement AJAX in Django. We need to use jQuery so as to write less javascript.
This is Contact example, which is the simplest example, I am using to explain the basics of AJAX and its implementation in Django. We will be making POST request in this example. I am following one of the example of this post: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django
models.py
Let's first create the model of Contact, having basic details.
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length = 100)
email = models.EmailField()
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.name
forms.py
Create the form for the above model.
from django import forms
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
exclude = ["timestamp", ]
views.py
The views look similar to the basic function-based create view, but instead of returning with render, we are using JsonResponse response.
from django.http import JsonResponse
from .forms import ContactForm
def postContact(request):
if request.method == "POST" and request.is_ajax():
form = ContactForm(request.POST)
form.save()
return JsonResponse({"success":True}, status=200)
return JsonResponse({"success":False}, status=400)
urls.py
Let's create the route of the above view.
from django.contrib import admin
from django.urls import path
from app_1 import views as app1
urlpatterns = [
path('ajax/contact', app1.postContact, name ='contact_submit'),
]
template
Moving to frontend section, render the form which was created above enclosing form tag along with csrf_token and submit button. Note that we have included the jquery library.
<form id = "contactForm" method= "POST">{% csrf_token %}
{{ contactForm.as_p }}
<input type="submit" name="contact-submit" class="btn btn-primary" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Javascript
Let's now talk about javascript part, on the form submit we are making ajax request of type POST, taking the form data and sending to the server side.
$("#contactForm").submit(function(e){
// prevent from normal form behaviour
e.preventDefault();
// serialize the form data
var serializedData = $(this).serialize();
$.ajax({
type : 'POST',
url : "{% url 'contact_submit' %}",
data : serializedData,
success : function(response){
//reset the form after successful submit
$("#contactForm")[0].reset();
},
error : function(response){
console.log(response)
}
});
});
This is just a basic example to get started with AJAX with django, if you want to get dive with several more examples, you can go through this article: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django
Easy ajax calls with Django
(26.10.2020)
This is in my opinion much cleaner and simpler than the correct answer. This one also includes how to add the csrftoken and using login_required methods with ajax.
The view
#login_required
def some_view(request):
"""Returns a json response to an ajax call. (request.user is available in view)"""
# Fetch the attributes from the request body
data_attribute = request.GET.get('some_attribute') # Make sure to use POST/GET correctly
# DO SOMETHING...
return JsonResponse(data={}, status=200)
urls.py
urlpatterns = [
path('some-view-does-something/', views.some_view, name='doing-something'),
]
The ajax call
The ajax call is quite simple, but is sufficient for most cases. You can fetch some values and put them in the data object, then in the view depicted above you can fetch their values again via their names.
You can find the csrftoken function in django's documentation. Basically just copy it and make sure it is rendered before your ajax call so that the csrftoken variable is defined.
$.ajax({
url: "{% url 'doing-something' %}",
headers: {'X-CSRFToken': csrftoken},
data: {'some_attribute': some_value},
type: "GET",
dataType: 'json',
success: function (data) {
if (data) {
console.log(data);
// call function to do something with data
process_data_function(data);
}
}
});
Add HTML to current page with ajax
This might be a bit off topic but I have rarely seen this used and it is a great way to minimize window relocations as well as manual html string creation in javascript.
This is very similar to the one above but this time we are rendering html from the response without reloading the current window.
If you intended to render some kind of html from the data you would receive as a response to the ajax call, it might be easier to send a HttpResponse back from the view instead of a JsonResponse. That allows you to create html easily which can then be inserted into an element.
The view
# The login required part is of course optional
#login_required
def create_some_html(request):
"""In this particular example we are filtering some model by a constraint sent in by
ajax and creating html to send back for those models who match the search"""
# Fetch the attributes from the request body (sent in ajax data)
search_input = request.GET.get('search_input')
# Get some data that we want to render to the template
if search_input:
data = MyModel.objects.filter(name__contains=search_input) # Example
else:
data = []
# Creating an html string using template and some data
html_response = render_to_string('path/to/creation_template.html', context = {'models': data})
return HttpResponse(html_response, status=200)
The html creation template for view
creation_template.html
{% for model in models %}
<li class="xyz">{{ model.name }}</li>
{% endfor %}
urls.py
urlpatterns = [
path('get-html/', views.create_some_html, name='get-html'),
]
The main template and ajax call
This is the template where we want to add the data to. In this example in particular we have a search input and a button that sends the search input's value to the view. The view then sends a HttpResponse back displaying data matching the search that we can render inside an element.
{% extends 'base.html' %}
{% load static %}
{% block content %}
<input id="search-input" placeholder="Type something..." value="">
<button id="add-html-button" class="btn btn-primary">Add Html</button>
<ul id="add-html-here">
<!-- This is where we want to render new html -->
</ul>
{% end block %}
{% block extra_js %}
<script>
// When button is pressed fetch inner html of ul
$("#add-html-button").on('click', function (e){
e.preventDefault();
let search_input = $('#search-input').val();
let target_element = $('#add-html-here');
$.ajax({
url: "{% url 'get-html' %}",
headers: {'X-CSRFToken': csrftoken},
data: {'search_input': search_input},
type: "GET",
dataType: 'html',
success: function (data) {
if (data) {
console.log(data);
// Add the http response to element
target_element.html(data);
}
}
});
})
</script>
{% endblock %}
I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:
ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin. If the request is an ajax request, it will not call the super.form_valid method, just call the form.save() directly.
from django.http import JsonResponse
from django import forms
from django.db import models
class AjaxableResponseMixin(object):
success_return_code = 1
error_return_code = 0
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
form.errors.update({'result': self.error_return_code})
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
if self.request.is_ajax():
self.object = form.save()
data = {
'result': self.success_return_code
}
return JsonResponse(data)
else:
response = super(AjaxableResponseMixin, self).form_valid(form)
return response
class Product(models.Model):
name = models.CharField('product name', max_length=255)
class ProductAddForm(forms.ModelForm):
'''
Product add form
'''
class Meta:
model = Product
exclude = ['id']
class PriceUnitAddView(AjaxableResponseMixin, CreateView):
'''
Product add view
'''
model = Product
form_class = ProductAddForm
When we use Django:
Server ===> Client(Browser)
Send a page
When you click button and send the form,
----------------------------
Server <=== Client(Browser)
Give data back. (data in form will be lost)
Server ===> Client(Browser)
Send a page after doing sth with these data
----------------------------
If you want to keep old data, you can do it without Ajax. (Page will be refreshed)
Server ===> Client(Browser)
Send a page
Server <=== Client(Browser)
Give data back. (data in form will be lost)
Server ===> Client(Browser)
1. Send a page after doing sth with data
2. Insert data into form and make it like before.
After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.
Or you can do with Ajax (Page will be not refreshed)
--------------------------
<Initialization>
Server ===> Client(Browser) [from URL1]
Give a page
--------------------------
<Communication>
Server <=== Client(Browser)
Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2]
Give a data struct(such as JSON)
---------------------------------
If you use Ajax, you must do these:
Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
Use Ajax to communicate with server using URL2. And then server send client a data struct.
Django is different from Ajax. The reason for this is as follows:
The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct. 
Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.
In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.
If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.
(My English is not good)

Categories