0

我用这个 form.py 制作了一个 Django 网站,用我当前的所有 spotify 播放列表填充一个带有下拉列表的模板 html:

from django import forms 
import spotipy
import spotipy.util as util


def getplaylists(): 

    #credentials
    CLIENT_ID='xxxxx'
    CLIENT_SECRET='xxxxx'
    USER='xxxxxx'

    # token krijgen
    token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    cache_token = token.get_access_token()
    sp = spotipy.Spotify(cache_token)

    # playlists opvragen
    results = sp.user_playlists(USER,limit=50)

    namenlijst = []
    idlijst = []

    for i, item in enumerate(results['items']):
        namenlijst.append(item['name'])
        idlijst.append(item['id'])

    #samenvoegen
    dropdowndata = zip(idlijst, namenlijst)
    #dropdowndata = zip(namenlijst, idlijst)

    return dropdowndata


class SpotiForm(forms.Form):  

    LIJSTEN = getplaylists()
    lijstje = forms.ChoiceField(choices=LIJSTEN, required=True)

我在我的 VPS 上运行这个 Django 网站的两个版本(使用完全相同的代码):
A)Apache2 上的一个版本(使用 mod_wsgi)
B)一个测试版本('python ./manage.py runserver xxxx:xxx')

当我在 Spotify 中添加或删除播放列表时,版本 A 的下拉列表会更新,但版本 B 的下拉列表不会。有人可以向我解释为什么会这样吗?

4

1 回答 1

2

因为在 Apache - 或任何适当的托管环境 - 一个进程持续多个请求,但在类或模块级别完成的任何操作每个进程仅执行一次。

像这样的动态事情应该在方法内部完成。在这种情况下,将其放在表单中__init__

class SpotiForm(forms.Form):  
    lijstje = forms.ChoiceField(choices=(), required=True)

    def __init__(self, *args, **kwargs):
        super(SpotiForm, self).__init__(*args, **kwargs)
        self.fields['lijstje'].choices = getplaylists()
于 2017-11-18T12:38:55.540 回答