来自模型的 ChoiceField - Django - MongoEngine

ChoiceField from model - Django - MongoEngine

我正在努力使这项工作成功,目前还没有成功。

我正在使用 Django 1.6.5 和 mongoengine 0.8.7。

我的 models.py 中有一些 ReferenceField 字段类型,我需要以 Choice Field 类型显示到 forms.py 文件中。

因此,这些选项必须用引用(或相关模型)中的 queryset 填充。因此,例如,当我选择在我的应用程序中注册某些内容时,我可以将 'users' 关联到 'brands' 或 'causes',等等...

无论如何,这是对我试图通过我的应用实现的目标的简要说明,这是我的 models.py:

from mongoengine import *


class Brand(DynamicDocument):
name = StringField(min_length=3,max_length=10,unique=True)
admins = ListField(ReferenceField("Peer", dbref=True))
campaigns = ListField(ReferenceField("Campaign"))
peers_partner =  ListField(ReferenceField("Peer"))
payments = ListField(ReferenceField("Payment_Campaign"))
medias = ListField(EmbeddedDocumentField("Media"))
description = StringField(min_length=10,max_length=500)
socials = ListField(DictField())

def __unicode__(self):
    return self.name

@property
def pic_profile(self):
    for x in self.medias:
        if x.tag == "profile":
            return x.url

@property
def pic_banner(self):
    for x in self.medias:
        if x.tag == "banner":
            return x.url

@property
def video_profile(self):
    for x in self.medias:
        if x.tag == "video":
            return x.url

如您所见,我的 class 上有一些 ReferenceField 字段,这些是与其他模型的关系,但我仍然无法尝试从 [=18] 中填充选择字段=] 有了这些参考,这是我的 forms.py:

from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Field, Div
from bson.objectid import ObjectId
from mongoengine.queryset import Q
from mongoengine import *
from hdb.brand.models import *

class Form_save_brand(forms.Form):
    name = forms.CharField()
    admins =  forms.ModelChoiceField(queryset=Brand.objects.get_or_create(id=Peer),empty_label="")
    campaigns = forms.ChoiceField()
    peers_partner = forms.ChoiceField()
payments = forms.ChoiceField()
medias = forms.ChoiceField()
socials = forms.ChoiceField()

    def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('instance', None)
        super(Form_save_brand, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields['name'].initial = self.instance.name
            self.fields['admins'].initial = self.instance.admins
            self.fields['campaigns'].initial = self.instance.campaigns
            self.fields['peers_partner'].initial = self.instance.peers_partner
            self.fields['payments'].initial = self.instance.payments
            self.fields['medias'].initial = self.instance.medias
            self.fields['socials'].initial = self.instance.socials

    def save(self, commit=True):
        brand = self.instance if self.instance else Brand()
        brand.name = self.cleaned_data['name']
        brand.admins = self.cleaned_data['admins']
        brand.campaigns = self['campaigns']
        brand.peers_partner = self.cleaned_data['peers_partner']
        brand.payments = self.cleaned_data['payments']
        brand.medias = self.cleaned_data['medias']
        brand.socials = self.cleaned_data['socials']
        if commit:
            brand.save()

        return brand

我正在做测试的唯一领域是第一个 ReferenceField(管理员),这是我被困的地方,如果我设法解决这个问题,我可以继续其他的。

这是 Django 的回溯:

NameError at /brand/nuevo/
name 'Peer' is not defined
Request Method: GET
Request URL:    http://localhost:9000/brand/nuevo/
Django Version: 1.6.5
Exception Type: NameError
Exception Value:    
name 'Peer' is not defined
Exception Location: /home/kkoci/hipeers/hweb/hweb/hweb/brand/forms.py in   Form_save_brand, line 11
Python Executable:  /home/kkoci/hipeers/hweb/hipeersweb/bin/python

正如您现在所见,查询类似于 (id=Peer),但我已经尝试使用 (id=field)、(id=name) 等...但没有成功。

希望我已经解释清楚了...

有什么想法吗?

任何帮助将不胜感激,请我坚持下去。

提前致谢!

编辑

这就是我在 views.py 中初始化表单的方式:

class AddBrand(CreateView):
model = Brand
form_class = Form_save_brand

def get_template_names(self):
    return ["brand/brand_nuevo.html"]

def get_success_url(self):
    return reverse('list')

def brand_valid(self, form):
    self.object = form.save(commit=False)
    self.object.user = self.request.user
    messages.success(self.request, "The brand has been created.")
    return super(AddBrand, self).brand_valid(form)

然后在模板中brand/brand_nuevo.html:

{% extends "base.html" %}
{% block body %}
<form action="." method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit"/>
</form>
{% endblock body %}

因此,您需要用特定的对等实例化 Form_save_brand,这样您就可以计算出依赖关系和显示的内容。可以这样实现(大部分代码保持不变)

您必须将表格更改为以下内容:

class Form_save_brand(forms.Form):
    name = forms.CharField()

    campaigns = forms.ChoiceField()
    peers_partner = forms.ChoiceField()
    payments = forms.ChoiceField()
    medias = forms.ChoiceField()
    socials = forms.ChoiceField()

    def __init__(self, peer, *args, **kwargs):
        # we pass a peer parameter that will be used in the queryset query
        self.instance = kwargs.pop('instance', None)
        self.fields['admins'] = forms.ModelChoiceField(queryset=Brand.objects.get_or_create(id=peer),empty_label="")

然后,在您看来

class AddBrand(CreateView):
    model = Brand
    # you don't need a form class here
    def get_form(self, form_class=None):
        return Form_save_brand(<you set the peer value here>, **self.get-form_kwargs())