Django-nonrel using ListField containing EmbeddedObjects in the admin

我的梦境 提交于 2019-12-12 17:14:21

问题


I've been trying hopelessly to get this to work.

I have a model that contains a ListField of EmbeddedObjects, basically it's an Item in an auction that contains a list of bids within it. Typycal MongoDB approach.

I understand that ListField doesn't show up in the admin since it doesn't know what Widget to display, it could be a list of anything. That makes sense.

I've created a fields.py in my app folder and subclassed ListField and I'm now using this in my models.py

My question is:

  • How do I keep going from this point onwards until getting a widget on my admin page under the Item section where I can add bids to the Item selected?

Here's my model.py

from django.db import models
from djangotoolbox.fields import ListField
from djangotoolbox.fields import EmbeddedModelField
from ebay_clone1.fields import BidsListField

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=75)
    def __unicode__(self):
        return self.name

class Item(models.Model):
    seller = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(max_length=100)
    text = models.TextField()
    price = models.FloatField()
    dated = models.DateTimeField(auto_now=True)
    num_bids = models.IntegerField()
    bids = BidsListField(EmbeddedModelField('Bid'))
    item_type = models.CharField(max_length=100)
    def __unicode__(self):
        return self.title


class Bid(models.Model):
    date_time = models.DateTimeField(auto_now=True)
    value = models.FloatField()
    bidder = models.ForeignKey(User, null=True, blank=True)

In my fields.py I have:

from django.db import models
from djangotoolbox.fields import ListField
from djangotoolbox.fields import EmbeddedModelField
from django import forms

class BidsListField(ListField):
    def formfield(self, **kwargs):
        return None

class BidListFormField(forms.Field):
    def to_python(self, value):
        if value in validators.EMPTY_VALUES:
            return None
        return value

    def validate(self,value):
        if value == '':
            raise ValidationError('Empty Item String?')

回答1:


Try this?

class BidsListField(ListField):
    def formfield(self, **kwargs):
        return BidListFormField(**kwargs)


来源:https://stackoverflow.com/questions/8909408/django-nonrel-using-listfield-containing-embeddedobjects-in-the-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!