如何使用 ModelMultipleChoiceField 保存表单?

发布于 2024-08-12 17:51:14 字数 1249 浏览 1 评论 0原文

我有一个模型日历,并且我希望能够以某种形式创建它的多个实例。

这是我的模型:

class Event(models.Model):
    user = models.ForeignKey(User)

class Group(models.Model):
    name = models.CharField(_('Name'), max_length=80)
    events = models.ManyToManyField(Event, through='Calendar')

class Calendar(models.Model):
    event = models.ForeignKey(Event)
    group = models.ForeignKey(Group)

class CalendarInline(admin.TabularInline):
    model = Calendar
    extra = 1

class GroupAdmin(admin.ModelAdmin):
    inlines = (CalendarInline,)

这是我尝试编写表单的方式:

class AddEventToGroupForm(ModelForm):
    group = ModelMultipleChoiceField(queryset=Group.objects.all(), widget=SelectMultiple())

    def save(self):
        for g in self:
            g.save()

    class Meta:
        model = Calendar
        fields = ('group',)

这是我的观点的一部分:

e = Event.objects.get(id=event_id)
calentry = Calendar(event=e)
if request.POST:
    f = AddEventToGroupForm(data=request.POST, instance=calentry)
    if f.is_valid():
        f.save()

如果我尝试提交该表单,我得到:

AttributeError at /groups/add_event/7/

'BoundField' object has no attribute 'save'

在此创建日历的多个实例的正确方法是什么 情况?

I have a model Calendar and in a form I want to be able to create multiple instances of it.

Here are my models:

class Event(models.Model):
    user = models.ForeignKey(User)

class Group(models.Model):
    name = models.CharField(_('Name'), max_length=80)
    events = models.ManyToManyField(Event, through='Calendar')

class Calendar(models.Model):
    event = models.ForeignKey(Event)
    group = models.ForeignKey(Group)

class CalendarInline(admin.TabularInline):
    model = Calendar
    extra = 1

class GroupAdmin(admin.ModelAdmin):
    inlines = (CalendarInline,)

Here is how I try to code my form:

class AddEventToGroupForm(ModelForm):
    group = ModelMultipleChoiceField(queryset=Group.objects.all(), widget=SelectMultiple())

    def save(self):
        for g in self:
            g.save()

    class Meta:
        model = Calendar
        fields = ('group',)

And here is a part of my view:

e = Event.objects.get(id=event_id)
calentry = Calendar(event=e)
if request.POST:
    f = AddEventToGroupForm(data=request.POST, instance=calentry)
    if f.is_valid():
        f.save()

If I try to submit that form, I get:

AttributeError at /groups/add_event/7/

'BoundField' object has no attribute 'save'

What is the proper way to create multiple instances of Calendar in this
situation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

未央 2024-08-19 17:51:14

这不是处理表单中多对多关系的方法。您无法迭代表单中的字段并保存它们,这确实行不通。

在这种形式中,只有一个字段,而该字段恰好有多个值。这里要做的事情是迭代该字段的,您可以在cleaned_data字典中找到这些值(当表单有效时)。

因此,在您看来,您可以执行以下操作:

if f.is_valid():
    for group in f.cleaned_data['group']:
        calentry.groups.add(group)

请注意,您根本没有“保存”AddEventToGroupForm 表单。我会将其设为标准 forms.Form,而不是 ModelForm,因为您并不真正依赖于任何 ModelForm 功能。

That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way.

In this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll find in the cleaned_data dictionary (when the form is valid).

So, in your view, you do something like:

if f.is_valid():
    for group in f.cleaned_data['group']:
        calentry.groups.add(group)

Note you're not 'saving' the AddEventToGroupForm form at all. I would make it a standard forms.Form, rather than a ModelForm, as you're not really depending on any of the ModelForm functionality.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文