来自模型的ChoiceField - Django - MongoEngine

时间:2015-01-20 19:09:36

标签: python django forms mongodb mongoengine

我试图做这项工作,到目前为止没有成功。

我使用的是Django 1.6.5和mongoengine 0.8.7。

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

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

无论如何,这是对我尝试使用我的应用程序实现的内容的简要说明,这里是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

正如您所看到的,我的课程中有一些ReferenceField字段,这些字段是与其他模型的关系,但我仍然试图用forms.py填充选项字段引用,这里是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 %}

1 个答案:

答案 0 :(得分:1)

因此,您需要的是使用特定的对等实例化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())