jundymek
jundymek

Reputation: 1043

Python/Django data to jquery alert box

I have a function which get some data. Result is for example:

sites = Site.objects.filter(is_active=False)

Function runs after button is pressed in django admin.py:

def my_function(self, request):
    sites = Site.objects.filter(is_active=False)
    return HttpResponseRedirect(request.META["HTTP_REFERER"], {'result': sites})

def get_urls(self):
    urls = super(ConfigAdmin, self).get_urls()
    my_urls = [
        url(r'^my_function/$', self.export),
    ]
    return my_urls + urls

This is my button code:

<input type="submit"  onclick="location.href='my_function/'" value="{% trans 'My_function' %}" />

I would like to put result to jquery alert box. How can I achieve that?

Upvotes: 0

Views: 637

Answers (2)

jundymek
jundymek

Reputation: 1043

I made it that way. It works but I don't know is it a proper way:

my admin.py:

def my_function(self, request):
    sites = Site.objects.filter(is_active=False)
    if request.is_ajax():
        message = sites
        return HttpResponse(message)
    else:
        return HttpResponseRedirect(request.META["HTTP_REFERER"])

my .js file:

$('#content > p > input[type="submit"]:nth-child(2)').click(function() {
        $.get("my_function/", function (data) {
        alert(data);
    });
    });

my template file:

<input type="submit"  onclick="location.href='my_function/'" value="{% trans 'My_function' %}" />

Is it ok? It displays alert box with variable from my function.

Upvotes: 0

Brobin
Brobin

Reputation: 3326

Firstly, your view needs to return a valid json object so that the jquery callback can process it. Django has a built-in JsonResponse that we can use to serialize our data.

from django.http import JsonResponse

def my_function(self, request):
    sites = Site.objects.filter(is_active=False).values_list('name', flat=True)
    return JsonResponse({'result': sites}, safe=False)

Now, we need to show this on the page with jquery. You can do this by binding a click callback to a link, and alerting the result of the view.

<a href="#" id="my-button">{% trans 'My_function' %}</a>

<script>
$('#my-button').click(function(){
    $.get('my_function/', function(data){
        alert(data.result);
    });
});
</script>

Upvotes: 1

Related Questions