Django

Django

Explore django code snippets and tutorials

Django

Django render ajax function

<p>This code is a Django view function that handles AJAX requests and returns a JSON response containing an HTML template rendered with the given context if the request is an …

python
1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from django.http import JsonResponse
from django.template.loader import render_to_string
def render_ajax(request, template, context):
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if is_ajax:
        ajax_template = render_to_string(template, context)
        return JsonResponse({'template':ajax_template})
    return render(request, template,context)
Django

Django function to create query string

<p>The <code>create_query_string</code> function appears to be a Python function that takes a <code>request</code> object as input and generates a query string from the parameters in the request&#39;s <code>GET</code> parameters. This …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def create_query_string(request):
    query_params = []

    for key in request.GET.keys():
        if key != 'page':
            values = request.GET.getlist(key)
            for value in values:
                if value:
                    query_params.append("{}={}".format(key, value))

    query_string = "&".join(query_params)
    return query_string
Django

Django ajax post form

<p>The code you provided is a JavaScript/jQuery script that handles form submission and AJAX requests. It seems to be a client-side script that interacts with a server to handle form …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$('body').on('submit', 'form', function(e){
        e.preventDefault();
        $('input, select').removeClass('is-invalid');
        $( ".invalid-feedback" ).remove();
        var $form = $(this);
        var data = $form.serialize();
        var url_link = $form.attr('action');
        $.when($.ajax({
          url: url_link,
          data:data,
          method:  $form.attr('method'),
          datatype: 'json',
        })).then(function( response, textStatus, jqXHR ) {
        var obj = JSON.parse(response);
        console.info(obj)
        $('form')[0].reset();
        var app = obj[0].model.split('.')[0];
        var model = obj[0].model.split('.')[1];
        console.info("app:" + app);
        console.info("model:" + model);
        $("[id$='"+ model + "-list']").prepend("<li>" + obj[0].fields['name'] + "</li>");
      }).catch(function(err){
        $.each(err.responseJSON, function(index, value){
          console.info(index, value);
          $('#id_'+ index).addClass('is-invalid');
          $('#id_'+ index).after("<div class='invalid-feedback'>" + value + "</div>");
        });
      });
    })
Django

Django Ajax Mixin helpers

<p>These code snippets are mixins for Django views, allowing them to handle AJAX requests for displaying and processing data.</p> <ol> <li><code>AjaxListMixin</code>: This mixin is designed to handle AJAX requests for …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class AjaxListMixin:
    def get(self, request, *args, **kwargs):
        self.object_list = self.get_queryset()
        if request.is_ajax():
            data = serializers.serialize("json", self.object_list)
            return JsonResponse(data, safe=False)
        context = self.get_context_data()
        return self.render_to_response(context)


class AjaxFormMixin:
    def form_valid(self, form):
        form.save()
        if self.request.is_ajax():
            data = serializers.serialize("json", [form.instance])
            return JsonResponse(data, safe=False, status=200)
        return super().form_valid(form)

    def form_invalid(self, form):
        if self.request.is_ajax():
            return JsonResponse(form.errors, safe=False, status=400)
        return super().form_invalid(form)