【问题标题】:Django: error when using ModelChoiceField with MongoEngineDjango:将 ModelChoiceField 与 MongoEngine 一起使用时出错
【发布时间】:2015-08-06 06:32:30
【问题描述】:

我必须使用 Django 开发一个 Web 界面,并且我试图在 HTML 中显示一个选择列表,其中填充了从 MongoDB 查询中获得的值,但是我遇到了一些问题。我正在使用 MongoEngine。 我的 forms.py 看起来像这样:

class top_hashtags(forms.Form):
    top_hashtags_collection = forms.ModelChoiceField(queryset=Collections.objects.all(), required=True)

在views.py中我这样做:

def index(request):
    form = top_hashtags()
    return render(request, 'index.html', {'user':1, 'top_hashtags_form': form}, context_instance=RequestContext(request))

然后,在 index.html 中我尝试了选项:

  • 如果我使用{{ top_hashtags.as_p }},我会得到一个 Collections 对象列表。如果我点击提交,表单不会通过验证。
  • 如果我使用这样的东西:

<td>
  <ul>
    {% for choice in top_hashtags.top_hashtags_collection.field.queryset %}
    <li>
      <input type="radio" name="top_hashtags_collection" value="{{choice.collection_name}}" />
      <label for="">{{choice.collection_name}}</label>
    </li>
    {% endfor %}
  </ul>
</td>

它正确显示了选项,但单击“提交”按钮时我得到AttributeError at /top_hashtags_form 'QuerySet' object has no attribute 'model'

我想要的只是在服务器端获得用户的销售(显然)。

我尝试了很多方法,但我找不到解决方案。我想这是愚蠢的,但我无法找到。任何帮助将不胜感激。提前谢谢你。

【问题讨论】:

  • 我上次检查时无法在 mongoengine 中使用 django 的默认表单。 Check this out.
  • 非常感谢@sobolevn。最后,我能够以另一种方式解决它。我会将其发布为答案。

标签: python django mongodb mongoengine


【解决方案1】:

我能够解决问题。这可能不是最优雅的方式,但它确实有效:

class clean_collection(forms.Form):
    OPTIONS = ()
    OPTIONS = list(OPTIONS)
    queryset = Collections.objects.all()
    for q in queryset:
        OPTIONS.append((q.collection_name, q.collection_name))
    OPTIONS = tuple(OPTIONS)
    coleccion = forms.ChoiceField(widget=forms.Select,
                                         choices=OPTIONS)
    keyword = forms.CharField(required=False)

在我的 index.py 中,我只使用 {{ form.as_p }}

希望对遇到同样问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多