Django-ratings - 404 error "Invalid model or app_label"? Why? - django

Can someone help me with Django-ratings app? I'm trying to post a rating but the app doesn't seem to do anything. What part am I missing here? Really hard to find examples out there..
My function looks like this (jquery Raty plugin):
$('.raty').raty({
click: function(score, evt) {
var vote_url = "/rate/" + $(this).attr('value') + "/" + score + "/" ;
$.ajax({
url: vote_url,
type: "GET",
success: function(){
alert('Vote successful!');
}
});
}
});
The GET seems to work but i can see in my admin that no votes/scores are registered.
In my URL:
url(r'rate/(?P<object_id>\d+)/(?P<score>\d+)/', AddRatingFromModel(), {
'app_label': 'myapp',
'model': 'MyModel',
'field_name': 'rating',
}),
EDIT:
I'm getting a 404 error "Invalid model or app_label". But I'm pretty sure thoose are the correct ones.

This applications does not need the POST request. The easiest way to solve the problem is to set 'GET' method in ajax request
$.ajax({
...
type: 'GET'
...
To avoid 404 you need to write model name in lowercase. In django.contrib.contenttypes app_label and model use lowercase.
url(r'rate/(?P<object_id>\d+)/(?P<score>\d+)/', AddRatingFromModel(), {
...
'model': 'mymodel',
...
}),

Related

Avoid double call GET Ajax load

Well, I'm trying to create a graphical interface for a database using django.
I have to say that I'm trying to learn so I don't have too much experience with Frameworks, just with pure code.
The doubt I have is:
-When trying to create a filter system with checkboxes I have used Ajax to be able to update the view without having to refresh. Like this:
$(document).on('click','#console_check_filter',function(){
var ps_id;
ps_id = $(this).attr("data-posts-id");
$.ajax({
url: "{% url 'list-view' %}",
method: 'POST',
data: {
'getfilter': ps_id,
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function (res, status,data) {
$("#list").load("/game/list-view");
},
error: function (res,ras,rus) {
}
});
});
But I had the error that for every call I made with POST the AJAX function ().load() made another call which eliminated the variable that gave me the POST. This made it impossible for me to use the information received from the POST to create the filter.
Result: I click on the checkbox and in the console I get a call with the filtered list and then another one without filter, and as it is not only the last one that is rendered, which has no data.
To solve this I have used a globar variable to save the value in the POST and the ().load() return to make the GET call using the value saved in the GLOBAL.
filet=""
def game_list(request):
global filet
context = {}
game_filter = request.GET.get('console_check_filter')
games = Game.objects.all()
game_post = games
data = {'success': False}
page = request.GET.get('page',1)
game_console_filter=""
context['games'] = games
#if request.method=='POST':
game_console_filter = request.POST.get('getfilter')
if not game_console_filter:
game_console_filter = request.GET.get('getfilter')
if request.method=="POST":
filet = get_game_console_filter(request,game_console_filter)
context['games'] = games
context['game_post'] = filet
return render(request,'Jocs/list-view.html',context )
This doesn't seem elegant to me, I'm out of the woods, yes, but I don't think it's the best solution.
Any idea to avoid this happening to me?
A greeting and thank you very much for everything
Apparently I am more stupid than I thought. In the end the solution was to send the variable by URL. Example:
AJAX:
$(document).on('click','#console_check_filter',function(){
var ps_id;
ps_id = $(this).attr("data-posts-id");
$.ajax({
url: "{% url 'list-view' %}",
method: 'POST',
data: {
getfilter': ps_id,
csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function (res, status,data) {
$("#list").load("/game/list-view/?filters="+ps_id); > <-----HERE
},
error: function (res,ras,rus) {
}
});
});
views.py:
#if request.method=='POST':
game_console_filter = request.POST.get('getfilter')
if not game_console_filter:
game_console_filter = request.GET.get('filters') <---HERE
I think that if this is the right way to proceed, at least it's more elegant.
I hope someone else will find this answer useful.
Sorry for the inconvenience and for asking trivial questions. Greetings to all.

csrf error while trying to delete an object with ajax

I have all the objects from my db rendered on my template by an ajax function.
Near every object there's a button that should delete it from the db but since I'm working on Django it raise a csrf_token missing or incorrect error.
I'm not using a form so I don't know how to include the csrf_token.
var $orders = $('#orders')
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json',
success: function(orders) {
$.each(orders, function(i, order){
$orders.append('<li>name: '+order.name+', drink:
'+order.drink+'</li>')
$orders.append("<button data-id=" +(order.pk)+"
class='remove'>X</button>")
});
},
error: function() {
alert('errore caricamento ordini');
}
});
$orders.delegate('.remove', 'click', function(){
$.ajax({
type: 'DELETE',
url: 'http://127.0.0.1:8000/MyApp/list-api/' +
$(this).attr('data-id')
});
});
When I press a remove button a new request appears in the network panel of the browser, the response states :detail: "CSRF Failed: CSRF token missing or incorrect." The console gives a 403 forbidden error.
Any help or hints are really appreciated.

How should I POST and serialize and array of arrays with DRF?

I'm having an issue POST-ing a JSON object that contains and array of arrays and deserializing it using Django Rest Framework.
The idea here is that there can be a dynamic number of players (players: 2) and a list of lists/array of arrays of weapons that the players have (player_weapons [[], []]).
//javascript on client
var post_data = {
players: 2,
player_weapons: [
["sword", "shield"],
["mace", "slingshot"],
]};
var results = jQuery.post( url, post_data );
#serializers.py
class GameSerializer(serializers.Serializer):
players = serializers.IntegerField(min_value=1)
player_weapons = serializers.ListField(
child=serializers.ListField(
child=serializers.CharField(min_length=1, allow_blank=True),
min_length=0,
required=False),
min_length=0,
required=False
)
The request.POST I get is:
<QueryDict: {'runs': ['1000'], 'additional_players': ['2'],
'player_weapons': ['sword,shield', 'mace,slingshot']}>
What's really weird is that when I do request.POST['player_weapons'] I get:
mace,slingshot
whereas I'm expecting/hoping to get:
[['sword', 'shield'], ['mace', 'slingshot']]
Any help on how I should be structuring the POST and handling it in DRF would be awesome.
Thanks to RishiG for the help here.
Problem was that I wasn't specifying the contentType in the request. I slightly modified it to use jQuery's ajax request:
var posting = jQuery.ajax({
url: url,
type: "POST",
data: JSON.stringify(post_data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(){
}
});

flask endpoint for ajax call

I'm making an ajax call to my server while pressing submit button.
Button is present in page http://127.0.0.1:5000/post/15.
Jquery function invoked and the endpoint definition for submit_comment in python respectively:
function submit_comment(post_id) {
var uname = $('input[name="uname"]').val();
var comment = $('textarea[name="comment"]').val();
$.ajax({
url: "/submit_comment",
data: {name: uname, comment: comment, post_id: post_id},
method: "POST",
datatype: 'json',
success: function(response) {
console.log('reaches here');
addElement(response);
console.log('Is it me');
},
error: function(error) {
console.log('reached Error');
console.log(error);
}
});
}
py
#main.route('/submit_comment', methods = ['POST', 'PUT'])
def submit_comment():
entry = request.get_json(force=True)
print 'comment:', entry
....
Main is the blueprint. But I'm getting following 404 error.
127.0.0.1 - - [24/Aug/2017 10:30:55] "POST /post/submit_comment HTTP/1.1" 404 -
I am wondering from where this post got appended into the endpoint.
Can someone help me to understand the error and resolve it?
Thanks,
Deepak
I don't know a lot, but I know that the Flask docs on ajax say to query for the script root like this:
$SCRIPT_ROOT = {{ request.script_root|tojson }};
and then use that as part of the request URL.
An example from an ajax call I've used ($.getJSON being a jquery function for $.ajax)
$.getJSON($SCRIPT_ROOT + '{{ url_for("help_email") }}',

post data from ember js to python

iam using ember js with python and tornado server.
I want to send the json data from ember js to python.
here is what i have tried
App.MyleavesController = Ember.ObjectController.extend({
submitAction: function () {
data=[{fromdate:this.get("model.fromdate")}]
$.ajax({
type: "POST",
url: "/apply_leave",
data: JSON.stringify(data),
success: function ( data ) {
}
});
}
});
in my python it is
class LeaveFormHandler(tornado.web.RequestHandler):
def post(self):
print json.loads(data)
but i could not get data..
it says " global name 'data' is not defined"
am a newbie please help..
For a POST request, use json.loads(self.request.body). Arguments to post() are extracted from the url regex.