我是一名新开发者,我遇到了一个名为Chosen.js的javascript库,这对我的学校高级项目非常有用。我的问题是我有问题入门并让选择的表单显示使用django选择。我相信它与linting工具中出现的无效换行有关,我错过了其他的东西。
在pip install django-selected之后我已经选择了我在settings.py中安装的文件,如下所示:
INSTALLED_APPS = [
'django_python3_ldap',
'chosen',
'django_extensions',
'django_filters',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
然后我创建了我选择的表单:
from django import forms
from .models import User, FacilityDimension
from django.forms import ModelForm
from widgets import ChosenSelectMultiple
from chosen import forms as chosenforms
class ChosenModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ChosenModelForm, self).__init__(*args, **kwargs)
for field in self.fields:
if self.fields[field].__class__.__name__ in ['ChoiceField', 'TypedChoiceField', 'MultipleChoiceField']:
choices = self.fields[field].choices
self.fields[field] = chosenforms.ChosenChoiceField(choices=choices)
elif self.fields[field].__class__.__name__ in ['ModelChoiceField', 'ModelMultipleChoiceField']:
queryset = self.fields[field].queryset
self.fields[field] = chosenforms.ChosenModelChoiceField(queryset=queryset)
class FormFacilityDimension(ChosenModelForm):
class Meta:
model = FacilityDimension
创建表单后,我在模板中使用以下内容,但没有收到任何错误,但我无法显示错误:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.js" type="text/javascript"></script>
<script src="chosen.jquery.js" type="text/javascript"></script>
{% block extra_js %}
{{ block.super }}
{{ form.media }}
{% endblock %}
I added the following javascript file, however my linting tool is showing invalid line break the first line which i can't seem to get rid of this may have something to do with my problem:
$(document).ready(function () {
$('#id_coid_name').chosen();
}
)
;
我觉得好像我错过了一个步骤,在线教程主要与django_admin有关,看起来不完整。任何建议让我开始和运行将不胜感激。
To expand on this i'm now getting the following error after adjusting my script tags.
[04/Jan/2018 14:20:19] "GET /account/profile/chosen.jquery.js HTTP/1.1" 404 2849
Not Found: /account/profile/chosen.jquery.js
[04/Jan/2018 14:20:19] "GET /account/profile/chosen.jquery.js HTTP/1.1" 404 2849
[04/Jan/2018 14:20:22] "GET /account/profile/ HTTP/1.1" 200 20109
Not Found: /account/profile/chosen.jquery.js
[04/Jan/2018 14:20:22] "GET /account/profile/chosen.jquery.js HTTP/1.1" 404 2849
出于某种原因,当文件位于security / accounts / js /时,它正试图在/ account / profile中找到它。我怎么能改变这个?
答案 0 :(得分:1)
您的js脚本应与您网站的其他静态文件(css和图像)一起存在于静态文件夹中。这一行:
<script src="chosen.jquery.js" type="text/javascript"></script>
导致脚本相对于当前页面的路径加载。你应该用
替换<script src= "{% static ‘security/accounts/js/chosen.jquery.js’ %}" type="text/javascript"></script>
或者相对于您STATIC_URL保存脚本的路径。