简体   繁体   English

如何在Django-form下拉列表中刷新值?

[英]How to refresh values in Django-form dropdown list?

In my django project I have a form with dropdown list of options from database. 在我的django项目中,我有一个表单,其中包含数据库中的选项下拉列表。 When server starts up all options are there, but if there is an option added while it runs, the new option won't show up in dropdown list. 当服务器启动时,所有选项都在那里,但如果在运行时添加了一个选项,则新选项将不会显示在下拉列表中。

forms.py forms.py

class filter(forms.Form): 
    filterOption=forms.CharField(widget=forms.Select(choices=getOptions())

functions.getOptions() returns a list of options from mySQL (database is not the problem here). functions.getOptions()返回mySQL中的选项列表(数据库不是问题)。 It is then rendered in views.py and put into html form. 然后在views.py中呈现它并放入html表单。

from .forms import filter

def index(request):
    filter = filter()
    return render(request, 'homePage/home.html',{'filter':filter})

I understand that the form object is created when the server starts, but if a new option is added and getOptions() should return one more option, how can I re-initialise that form object without restarting the server. 我知道表单对象是在服务器启动时创建的,但是如果添加了一个新选项并且getOptions()应该再返回一个选项,那么如何在不重新启动服务器的情况下重新初始化该表单对象。 Sometimes it is added after ~10min, but I need it instantly. 有时它会在~10分钟后添加,但我需要立即使用它。

You can use ChoiceField with a callable: 您可以将ChoiceField与可调用ChoiceField一起使用:

class filter(forms.Form): 
    filterOption = forms.ChoiceField(choices=getOptions)

Well, if you want to show the new checkbox possibilities after you reload the form html page in your browser, it should be there immediately. 好吧,如果你想在浏览器中重新加载表单html页面后显示新的复选框可能性,它应该立即存在。

Have you really looked in the database that this option was added successfully? 您是否真的在数据库中查找过成功添加此选项的情况?

Do you have some kind of customized cache active? 您是否有某种自定义缓存活动?

If you want to show the new checkbox option without a page reload, you'd need to implement a pretty complicated custom form rendering which reloads the form every X seconds via an AJAX request. 如果要在没有页面重新加载的情况下显示新的复选框选项,则需要实现一个非常复杂的自定义表单呈现,它通过AJAX请求每隔X秒重新加载一次表单。

Solved it by following: https://modwsgi.readthedocs.io/en/develop/user-guides/reloading-source-code.html 解决了以下问题: https//modwsgi.readthedocs.io/en/develop/user-guides/reloading-source-code.html

I basicly kill the process and make it reload every time new value is added. 我基本上会杀死进程并在每次添加新值时重新加载。

import signal, os
os.kill(os.getpid(), signal.SIGINT)

In linked documentation it says 'touch'-ing the wsgi.py file should make it reload. 在链接文档中,它说“触摸”wsgi.py文件应该重新加载。 And it does, but only when you do it manualy, not if you use os.system('touch .../wsgi.py'). 它确实如此,但只有当你使用os.system('touch ... / wsgi.py')时才会这样做。 To make it reload with code I had to kill the process. 为了使用代码重新加载,我必须杀死进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM