简体   繁体   English

Django在ModelForm中添加ManyToManyField

[英]Django Adding a ManyToManyField to ModelForm

Sorry that this is like the thousandth question for this issue but I still can't see a light at the end of the tunnel. 抱歉,这就像该问题的千分之一的问题,但我仍然看不到隧道尽头的曙光。

Lets say I have two models: 可以说我有两个模型:

class Video(models.Model):
title = models.CharField(u"Titel",max_length=200)
slug = AutoSlugField(populate_from='title',unique=True)
date = models.DateField("Datum")
description = models.TextField(u"Beschreibung")
user = models.OneToOneField(User, blank=True, null=True)

class Channel(models.Model):
name = models.CharField(u"Name",max_length=30)
slug = AutoSlugField(populate_from='name',unique=True)
videos = models.ManyToManyField('videoportal.Video',related_name="contained_videos",blank=True,null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)

As you see I want to have a channel with video(s) in it. 如您所见,我想创建一个带有视频的频道。 So if I ad a video using a ModelForm like this 因此,如果我使用这样的ModelForm广告视频

class VideoForm(ModelForm):
    class Meta:
        model = Video

the form I get will not contain a input field to select a channel (of course not). 我得到的表格将不包含用于选择频道的输入字段(当然不是)。 So how can I do this? 那我该怎么做呢? How can I have a input field in my form to select one channel with a drop down? 如何在表单中有一个输入字段来选择一个带下拉菜单的通道?

Thanks, Philip 谢谢菲利普

If a video only belongs in one channel just give your Video model a ForeignKey to your Channel model. 如果视频只在一个频道所属只是给你的Video模型ForeignKey到你的Channel模式。 If it should belong to more than one channel I'd use a ManyToManyField in the Video model, as already suggested. 如果已经属于多个频道,则可以在Video模型中使用ManyToManyField

I think this would fit the idea of uploading videos and adding it to a channel far better than doing it the other way around. 我认为这比上传视频并将其添加到频道要好得多。

Use a custom form instead of Django ModelForm. 使用自定义表单而不是Django ModelForm。

probably something like this, 大概是这样的

class VideoForm(forms.Form):
    title = forms.CharField()
    description = forms.TextField()
    channel = forms.ModelChoiceField(queryset= Channel.objects.all(), empty_label=None)

do your validation in a view. 在视图中进行验证。 Use Model save() method to save information contained in your POSTed form. 使用Model save()方法可以保存POST表单中包含的信息。

Try putting the ManyToMany field in the Video model and omit it from the Channel model: 尝试将ManyToMany字段放入Video模型中,并从Channel模型中忽略它:


class Video(model.Model):
    ...
    channels = model.ManyToManyField('videoportal.Channel', related_name='videos')
    ...

If you want a simple dropdown to select a single channel, why is it a many-to-many realationship between videos and channels? 如果您希望通过简单的下拉菜单选择单个频道,为什么视频和频道之间会出现多对多的关系?

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

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