简体   繁体   English

Django:将ModelChoiceField与MongoEngine结合使用时出错

[英]Django: error when using ModelChoiceField with MongoEngine

I have to develop a web interface with Django and I am tryng to display a select list in HTML populated with values obtained from a MongoDB query, but I am facing some problems. 我必须使用Django开发一个Web界面,并且试图显示用从MongoDB查询获得的值填充的HTML中的选择列表,但是我遇到了一些问题。 I am using MongoEngine. 我正在使用MongoEngine。 My forms.py looks like this: 我的forms.py看起来像这样:

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

And in views.py I do this: 在views.py中,我这样做:

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

Then, in index.html I have tried to options: 然后,在index.html中,我尝试了以下选项:

  • If I use {{ top_hashtags.as_p }} I get a list of Collections object. 如果我使用{{ top_hashtags.as_p }}得到Collections对象的列表。 If I click submit, the form doesn't pass validation. 如果我单击提交,则该表单不会通过验证。
  • If I use something like this: 如果我使用这样的东西:

 <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> 

It shows the options correctly but I get AttributeError at /top_hashtags_form 'QuerySet' object has no attribute 'model' when clicking the Submit button. 它正确显示了选项,但是在单击“提交”按钮时,我AttributeError at /top_hashtags_form 'QuerySet' object has no attribute 'model'

What I want is just getting user's sellection at server side (obviously). 我想要的只是在服务器端(显然)获得用户的选择。

I have tried many things, but I cannot find the solution. 我已经尝试了很多事情,但是找不到解决方案。 I guess it is something stupid, but I cannot find out. 我想这很愚蠢,但我找不到。 Any help will be appreciated. 任何帮助将不胜感激。 Thank you in advance. 先感谢您。

I was able to solve the problem. 我能够解决问题。 It might not be the most elegant way of doing it, but it works: 它可能不是最优雅的方法,但是它可以工作:

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)

At my index.py, I just use {{ form.as_p }} . 在我的index.py,我只使用{{ form.as_p }}

I hope it can help people who faces the same problem. 我希望它可以帮助面临同样问题的人们。

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

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