【问题标题】:How can I let a user to post several images to one model?如何让用户将多张图像发布到一个模型?
【发布时间】:2011-05-31 20:21:24
【问题描述】:

我有一个列表模型:

class Listing(models.Model):

    owner = models.ForeignKey(User, verbose_name=_('offerer'))
    title = models.CharField(_('Title'), max_length=255)
    slug = models.CharField(editable=False, max_length=255)
    price = models.PositiveIntegerField(_("Price"), null=True, blank=True)
    description = models.TextField(_('Description'))
    time = models.DateTimeField(_('Created time'), 
        default = datetime.now,
        editable = False
    )

然后我有一个ListingImage,其中包含列表的图片:

from photologue.models import ImageModel

class ListingImage(ImageModel):

    pictures = models.ForeignKey(Listing, related_name="images")

forms.py

class ListingForm(forms.ModelForm):

    class Meta:
        model = Listing
        exclude = ('owner',) 

    def __init__(self, *args, **kwargs):
        super(ListingForm, self).__init__(*args, **kwargs)

为什么在上传页面,没有上传图片的字段??

【问题讨论】:

  • 好吧,您的Listing 模型中没有图像字段,那么您为什么希望在ModelForm 中看到Listing 的图像字段呢?看看docs.djangoproject.com/en/dev/topics/forms/modelforms/…
  • 因为我使用的是 django-photologue,所以我认为这会带来照片字段。
  • ListingImage(Imagemodel) 正在使用 django-photologue 中的模型,所以 ...

标签: django image file-upload


【解决方案1】:

ListingImage 有一个ForeignKey to Listing,所以ModelForm 用于ListingListingImage 无关。

除了Listing 模型之外,您不应该期望Listing 模型的ModelForm 向您显示任何内容。 ListingImageListing 模型的反向关系。

如果这是ModelAdmin,您将让管理站点通过定义内联向您展示这些反向关系: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin

因为看起来你不是在谈论管理面板,所以你在看InlineModelFormsetshttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view

另外,您可以向我们展示您的观点,以便我们看到全貌。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 2019-01-24
    • 2016-04-11
    • 2021-10-04
    • 1970-01-01
    • 2016-05-02
    • 2011-01-29
    相关资源
    最近更新 更多