我正在尝试按照此 guide 在 Droplet 虚拟机 (DigitalOcean) 中部署我的 django 应用程序.
为此,我成功地使用了 nginx 和 Gunicorn。
我面临的问题是 django-select2并且表单的小部件始终显示“找不到结果”。给出 404 错误,而在我的本地环境中它工作完美!
我尝试实现缓存(希望它能解决问题),但事情变得更糟,因为启用缓存后,即使在本地,小部件似乎也不再工作。
现在是时候展示我到目前为止的代码了:
设置.py:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
},
'select2': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 60 * 60 * 24,
},
}
SELECT2_CACHE_BACKEND = 'select2'
这是按照显示的指南完成的代码 here
PS:请注意,使用 redis 而不是 memcached 会得到相同的结果
这是我的 nginx 配置:
server {
listen 80;
server_name 46.101.134.225;
client_max_body_size 2M;
location = /favicon.ico { access_log off; log_not_found off; }
location /static {
root /projectname;
}
location /media {
root /projectname/staticfiles;
}
location /assets {
root /;
}
location / {
include proxy_params;
proxy_pass http://unix:/projectname/projectname.sock;
}
}
这是我的gunicorn配置:
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/projectname
ExecStart=/projectname/bin/gunicorn --access-logfile - --workers 3 --bind unix:/projectname/projectname.sock projectname.wsgi:application
[Install]
WantedBy=multi-user.target
这是我的带有小部件的表单:
from django_select2.forms import ModelSelect2Widget, ModelSelect2MultipleWidget
...
class CompanyForm(BaseModeratedObjectForm):
...
city = forms.ModelChoiceField(widget=ModelSelect2Widget(
model=City, search_fields=['name__istartswith']
), queryset=City.objects.all(), required=False)
...
treatments = forms.ModelMultipleChoiceField(widget=ModelSelect2MultipleWidget(
model=Treatment, search_fields=['name__icontains']
), queryset=Treatment.objects.all(), required=False)
...
PS:请注意,在实现缓存之前,我获得了以下结果:
- 在我的本地环境中完美工作。
- 有时在生产环境中工作(有时打字时会出现数据)。
实现缓存后,不再起作用(在我的本地环境中手动导航到 select2 url,我可以看到它显示错误 field_id not found
编辑:
由于我的答案甚至在 github 上的 django-select2 存储库中也被接受,我已经对项目进行了拉取请求,更改了文档以注意到这种情况!
最佳答案
我终于解决了这个问题,问题是,在实现redis缓存时,系统找不到redis服务器。使用sudo apt-get install redis-server
解决了这个问题,同时使用了 redis 缓存!
关于Django-select2 抛出 'Results cannot be loaded.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460757/