【问题标题】:How to use jQuery on Django Media Form如何在 Django 媒体表单上使用 jQuery
【发布时间】:2021-09-29 14:35:52
【问题描述】:

我正在尝试通过 Media 元类在 Django 表单上注入额外的 javascript 和 jQuery。

我向 create.html 模板返回了一个表单,并且执行了 js 函数但没有执行 jQuery 函数。

用于模板的base.html:

...
{% block content %}
{% endblock %}
...
{% block javascript %}
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  ...
  <script type="text/javascript">
    console.log('base.html js');
  </script>
{% endblock javascript %}

创建.html:

{% extends "base.html" %}
{% load static %}
{% block javascript %}
  {{ block.super }}
  <script type="text/javascript">
    console.log('create.html js');
  </script>
{% endblock javascript %}
{% block content %}
  {% if form %}
    {{ form.media }}
    {% include 'form.html' %}
  {% endif %}
{% endblock content %}

form.html:

{% load static %}
{% block javascript %}
  {{ block.super }}
  <script type="text/javascript">
    console.log('create.html js');
  </script>
{% endblock javascript %}
...
{% for field in form %}
  {{ field|add_class:"form-control" }}
{% endfor %}

forms.py:

class PlaceForm(forms.ModelForm):
  class Media:
    js = (
        'js/custom_tag_widget.js',
    )

custom_tag_widget.js:

$(document).ready( function() {
  console.log('form media js');
});

我有这个控制台输出并出现错误:

form.html js
ReferenceError: $ is not defined
base.html js
create.html js

有人可以帮帮我吗?提前致谢。

【问题讨论】:

    标签: jquery django django-forms


    【解决方案1】:

    好像 jquery 没有正确加载。

    我猜这是因为您的自定义 js custom_tag_widget.js 在 https://code.jquery.com/jquery-3.3.1.min.js 之前加载。

    检查网络中文件的顺序。

    如果在您的自定义 js 之后加载 jquery,您可以在 HTML 文件中的块 javascript 之后移动块 content

    【讨论】:

      【解决方案2】:

      请检查开发工具中的Network标签,检查你的js文件是否没有返回404,custom_tag_widget.js的路径是否正确。

      另外,您的项目中的静态配置可能不正确。

      请查看https://docs.djangoproject.com/en/3.2/howto/static-files/

      【讨论】:

      • jquery也加载成功了吗?
      • 你可以尝试用纯js函数代替jquery,比如window.addEventListener('DOMContentLoaded', function(){ //你的代码});而不是 $(document).ready
      • 好的,这是一个选项,但我想学习如何在 Django Media Form 中使用 jQuery
      猜你喜欢
      • 2013-04-15
      • 2020-08-08
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 2020-09-29
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多