【问题标题】:Django ModelMultipleChoiceField gives me a ProgrammingErrorDjango ModelMultipleChoiceField 给了我一个 ProgrammingError
【发布时间】:2018-12-03 14:24:11
【问题描述】:

我想得到你的帮助,因为我遇到了一个让我觉得有点奇怪的问题。

我正在使用Django 1.11.16

我的 forms.py 文件中有这个类:

class PublicationStatForm(forms.Form):
    # publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id'))
    publication_list = forms.ModelMultipleChoiceField(
        queryset=Publication.objects.all().order_by('pub_id'),
        label=_('Publication Choice'),
        widget=ModelSelect2Widget(
            model=Publication,
            search_fields=['pub_id__icontains', 'title__icontains'],
            attrs={'data-placeholder': "Please select publication(s)"}
        )
    )

    def __init__(self, *args, **kwargs):
        super(PublicationStatForm, self).__init__(*args, **kwargs)

然后,在我的 views.py 文件中:

class StatsView(TemplateView):
    """ Create statistics pageview """
    template_name = 'freepub/stats.html'
    form_class = PublicationStatForm

    def get_context_data(self, **kwargs):
        subtitle = _("Statistics")
        context_data = super(StatsView, self).get_context_data(**kwargs)
        context_data['form'] = self.form_class()
        ...
        return context_data

最后在我的模板中,我只有:

<form class="date-form" method="GET">
   <div class="row">
      <div class="col-md-7">
        {{ form.publication_list }}
      </div>
   </div>
   <input id="submit-date-stats" type="submit" class="btn btn-default" name="SearchPublicationPeriod"
               value="{% trans 'Submit' %}"/><br/>
</form>

我不明白为什么,当我的表单中有这行时它可以工作:

# publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id'))

但是当我用这个替换这一行时:

publication_list = forms.ModelMultipleChoiceField(
    queryset=Publication.objects.all().order_by('pub_id'),
    label=_('Publication Choice'),
    widget=ModelSelect2Widget(
        model=Publication,
        search_fields=['pub_id__icontains', 'title__icontains'],
        attrs={'data-placeholder': "Please select publication(s)"}
    )
)

我遇到了这个问题:

Exception Type: ProgrammingError at /freepub/stats
Exception Value: relation "select_cache" does not exist
LINE 1: SELECT COUNT(*) FROM "select_cache"
                             ^

你有什么想法吗?

编辑:添加缓存设置

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    },
    # "default": {
    #     "BACKEND": "django_redis.cache.RedisCache",
    #     "LOCATION": "redis://127.0.0.1:6379/1",
    #     "OPTIONS": {
    #         "CLIENT_CLASS": "django_redis.client.DefaultClient",
    #     }
    # },
    'select': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'select_cache',
        'TIMEOUT': None,
    }
}

# Set the cache backend to select2
SELECT2_CACHE_BACKEND = 'select'

【问题讨论】:

  • 您是否运行过 makemigrations 和迁移?我看到代码差异在于形式,但值得先检查一下。
  • 我没有接触到我的 models.py 文件,但我可以试试。
  • 我认为不太可能,但值得一试。你设置了什么缓存后端,你能包括吗?
  • 是的,我可以,但是我在这个过程中没有处理缓存设置,所以我认为它不是从那个时候开始的?
  • 我认为可能是,之前一直在查看文档。 (顺便说一句,不错的图书馆,以前没有遇到过这个。)。我认为问题在于您的 select2 缓存后端应该是 select2 而不是 select - 这对于您收到 select_cache 不存在的错误是有道理的。

标签: django modelchoicefield modelmultiplechoicefield


【解决方案1】:

问题在于您的缓存设置。

虽然您已经设置了数据库缓存后端,但您需要运行 python manage.py createcachetable 才能在数据库中实际创建它,类似于运行 migrate 进行常规模型更改或添加的方式 - 这也是错误的原因看起来很相似,这让我一开始就走上了迁移路线。

Django ProgrammingError 异常是基本 DatabaseError 的扩展,因此它总是与数据库中的错误有关。 (source)

如果您使用 redis 或其他 KV 存储缓存,则不会出现这种情况,因为它会自动插入它。因为 Django 数据库缓存使用同一个数据库中的一个表,所以必须根据this section of the documentation 创建该表。

【讨论】:

  • 感谢您的评论,我没有关于缓存的问题。我会验证它,但我的表单仍然不起作用。也许我会创建一个新问题。
  • 谢谢!希望我也能提供帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2013-03-31
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多