skip to Main Content

UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
warnings.warn(

On HTML templates everything worked. After switching to AJAX, this error appeared
Tried these tips, did not help: How can I send a CSRF token in a form?. https://django.readthedocs.io/en/latest/howto/csrf.html.
addnew.html

{% load widget_tweaks %}

<form method="post" action="{% url 'table:addnew' %}" class="js-product-add-form">  
    {% csrf_token %}
    <div class="modal-header">
    <h5 class="modal-title modalLabel">Добавить запись</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    <div class="modal-body"> 
            
                {% for field in form %}
                <div class="form-group{% if field.errors %} has-error{% endif %}">
                  <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                  {% render_field field class="form-control" %}
                  {% for error in field.errors %}
                    <p class="help-block">{{ error }}</p>
                  {% endfor %}
                </div>
              {% endfor %}
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
                        <input type="submit" class="btn btn-primary" value="Добавить" />
                    </div> 
    </div> 
</form>  
 

views.py

def index(request):  
    snj = ScheduleNotJob.objects.all()  
    form = SNJ()   
    return render(request,"index.html",{'snj': snj, 'form':form})  


def save_product_form(request, form, template_name):
    data = dict()
    if request.method == 'POST':  
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            SNJ = ScheduleNotJob.objects.all()
            data['html_product_list'] = render_to_string('table.html', {
                'snj': SNJ
            })
        else:
            data['form_is_valid'] = False
    context = {'form': form}
    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)


def addnew(request):
    if request.method == 'POST':
        form = SNJ(request.POST)
    else:
        form = SNJ()
    return save_product_form(request, form, 'addnew.html')  


def edit(request, id):
    elem = ScheduleNotJob.objects.get(id=id)
    if request.method == "POST":
        form = SNJ(request.POST, instance=elem)  
    else:  
        form = SNJ(instance=elem)
    return save_product_form(request, form, 'edit.html')


def destroy(request, id):  
    snj = ScheduleNotJob.objects.get(id=id)  
    snj.delete()  
    return HttpResponseRedirect(reverse('table:index')) 

addnew.html

$(document).ready(function(){
    
    var loadForm = function () { 
      var btn = $(this);
      $.ajax({
        url: btn.attr("data-url"),
        type: 'get',
        dataType: 'json',
        beforeSend: function () {
          $("#modal-product .modal-content").html("");
          $("#modal-product").modal("show");
        },
        success: function (data) {
          $("#modal-product .modal-content").html(data.html_form);
        },
      
      });
    };
   

    var saveForm = function () {
      var form = $(this);
      $.ajax({
        url: form.attr("action"),
        data: form.serialize(),
        type: form.attr("method"),
        dataType: 'json',
        success: function (data) {
          if (data.form_is_valid) {
            $("#bootstrapdatatable tbody").html(data.html_product_list);
            $("#modal-product").modal("hide");
            table.draw();
          }
          else {
            $("#modal-product .modal-content").html(data.html_form);
          }
        }
      });
      return false;
    };

     // Add product
     $(".addSpan").on("click", loadForm);
     $("#modal-product").on("submit", ".js-product-update-form", saveForm);


    // Update product
    $("#bootstrapdatatable").on("click", ".editSpan", loadForm);
    $("#modal-product").on("submit", ".js-product-add-form", saveForm);
  });

2

Answers


  1. Your html page is rendered without RequestContext so:

    return render_to_response('yourpage.html', context_instance=RequestContext(request))
    

    add this render to your views.py where you render the html page.

    Login or Signup to reply.
  2. To fix this error as I mentioned in the comment, you can include the CSRF token in your AJAX request headers as follows

    var csrftoken = $("[name=csrfmiddlewaretoken]").val(); // get the CSRF 
    token value from the form
    $.ajaxSetup({
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", csrftoken); // include the CSRF token in the request headers
    }
    

    });

    and also you need to modify your view, you need to replace the render_to_string to render then only we can render the template with the CSRF token context processor

    the new view will be like follows

    def save_product_form(request, form, template_name):
    data = dict()
    if request.method == 'POST':  
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            SNJ = ScheduleNotJob.objects.all()
            data['html_product_list'] = render_to_string('table.html', {
                'snj': SNJ
            })
        else:
            data['form_is_valid'] = False
    context = {'form': form}
    data['html_form'] = render(request,template_name, context)
    return JsonResponse(data)
    

    sorry for the late response I saw your message now. Try this and give me an upvote if it works for you if you have any issue just comment I’ll try to figure out

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search