Django CSRF_令牌问题,仅限边缘

2024-10-02 12:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过不同的浏览器(Chrome、Firefox、IE11和Edge)尝试我的django应用程序,但是我遇到了一个只有csrf_tokenEdge的问题。在

这个问题是参考我的django表格。在

我的视图文件:

class ManageDocView(AdminRequiredMixin, View):
    """ Render the Admin Manage documents to update year in the filename"""

    template_name = 'omcl/manage_doc_form.html'
    form_class = ManageDocForm
    success_url = 'omcl/manage_doc_form.html'

    @staticmethod
    def get_title():
        return 'Change Document Title'

    def get(self, request):
        form = self.form_class()
        context = {
            "form": form,
            "title": self.get_title()
        }
        return render(request, self.template_name, context)

    def post(self, request):
        form = self.form_class()
        query_document_updated = None
        query_omcl = None
        query_document = None

        if "submitButton" in request.POST:
            omcl_list = request.POST.get('omcl_list', False)
            query_omcl = Omcl.objects.get(id=omcl_list)
            query_document = Document.objects.filter(omcl=omcl_list)
            form.fields['omcl_list'].initial = query_omcl

        elif "UpdateDocument" in request.POST:
            checkbox_id = request.POST['DocumentChoice']
            checkbox_id_minus_1 = int(checkbox_id) - 1
            query_document_updated = Document.objects.get(id=checkbox_id)

            omclcode = query_document_updated.omcl.code
            src_filename = query_document_updated.src_filename
            filename, file_extension = os.path.splitext(src_filename)
            category = query_document_updated.category

            if category == "ANNUAL":
                category = "ANNUAL_REPORT"

            year = self.request.POST['pts_years']

            # Create the new document title updated by the new year
            new_document_title = f"{year}_{category}_{omclcode}_{checkbox_id_minus_1} - {src_filename}"

            # Create the new document file updated by the new year
            new_document_file = f"omcl_docs/{omclcode}/{year}_{category}_{omclcode}_{checkbox_id_minus_1}{file_extension}"

            # Get file.name in order to rename document file in /media/
            document_path = query_document_updated.file.name

            try:
                actual_document_path = os.path.join(settings.MEDIA_ROOT, document_path)
                new_document_path_temp = f"{settings.MEDIA_ROOT}/{new_document_file}"
                new_document_path = os.rename(actual_document_path, new_document_path_temp)
            except FileNotFoundError:
                messages.error(self.request, _(f"Document {src_filename} doesn't exist on the server"))
                return redirect('manage_doc')
            else:
                # Assign modifications to selected document and save it into the database
                query_document_updated.title = new_document_title
                query_document_updated.file = new_document_file
                query_document_updated.save()
                messages.success(self.request, _(f"The modification has been taken into account"))

        context = {
            'form': form,
            'query_omcl': query_omcl,
            'query_document': query_document,
            'query_document_updated': query_document_updated,
            'title': self.get_title(),
        }
        return render(request, self.template_name, context)

我的表单文件:

^{pr2}$

我的模板文件中有一小部分javascript:

{% block extra_script %}
  <!-- Submit OMCL list with change and not submit button + Previous/Next pagination button -->
  <script>
    $('#select-omcl-form').on('change', function () {
      $(this).submit();
    });
  </script>
{% endblock %}

{% block main %}

  <h2>{{ title }}</h2>

  <div class="row manage-doc">

    <div class="col-md-12">
      <form id="select-omcl-form" name="select-omcl-form" action="" method="POST">
        {% csrf_token %}
        <fieldset>
          <legend><span class="name">{% trans 'Select an OMCL' %}</span></legend>
          {{ form.omcl_list }}
          <input type="hidden" name="submitButton">
        </fieldset>
      </form>
    </div>
  </div>
  <br/>

  <div class="row manage-doc">
    <div class="col-md-12">
      <fieldset>
        <legend><span class="name">{% trans 'Select a document' %}</span></legend>
        <form action="" method="POST">
          {% csrf_token %}
          <div id="table-document">
            <table id="document-table" class="table table-bordered table-striped table-condensed table_model">
              <thead>
              <tr>
                <th id="radio-column"></th>
                <th id="document-title-column">{% trans 'Document title' %}</th>
              </tr>
              </thead>
              <tbody>
              {% for document in query_document|dictsortreversed:'title' %}
                <tr>
                  <td><input type="radio" class="radio-document" id="document-radiobox" name="DocumentChoice"
                             value="{{ document.id }}"></td>
                  <td>{{ document.title }}</td>
                </tr>
              {% endfor %}
              </tbody>
            </table>
          </div>
          <br><br>

          <legend><span class="name">{% trans 'Select a new year' %}</span></legend>

          {{ form.pts_years }}

          <button class="btn btn-default" id="document-button" type="submit"
                  name="UpdateDocument">{% trans "Change year" %}</button>
        </form>
      </fieldset>
      <br>
    </div>
  </div>

{% endblock main %}

gif演示文稿:

这是一个小的gif,它解释了流程和问题,仅适用于边缘浏览器:

Link to my gif

我尝试了:

我试图在我的设置.py但它不起作用。在

你知道吗?这很奇怪,因为我对其他浏览器没有任何问题。只有Microsoft Edge。 我的浏览器允许使用Cookies。在


Tags: pathnameselfdivformidnewtitle
1条回答
网友
1楼 · 发布于 2024-10-02 12:37:49

多亏了我的同事,我发现了这个问题。我使用了redirect,但我必须使用render,因为如果我重定向,CSRF_TOKEN将不会实现,它将使用前一个令牌发送第二个POST请求。在

所以应该是:

except FileNotFoundError:
    messages.error(self.request, _(f"Document {src_filename} doesn't exist on the server"))
    context = {
          'form': form,
          'query_omcl': query_omcl,
          'query_document': query_document,
          'query_document_updated': query_document_updated,
          'title': self.get_title(),
          }
    return render(request, self.template_name, context)

而不是:

^{pr2}$

相关问题 更多 >

    热门问题