使用 forms.ModelMultipleChoiceField 的 Django 模型表单

发布于 2024-08-20 22:23:26 字数 1723 浏览 6 评论 0原文

我的 Django 应用程序中有一个 ModelForm,它使用 forms.ModelMultipleChoiceField,它在表单上显示为 forms.CheckboxSelectMultiple 小部件。此模型表单用于选择/取消选择多对多关系的值。问题是:当您取消选中所有复选框并保存表单时,它不会保存。如果取消选中除 1 之外的所有选项,它会正确保存。

关于模型形式和多对多关系,我是否缺少任何技巧?我遇到了错误吗?我是姜戈的新手。提前致谢。

自定义字段:

class NetworkMessageChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.display_message    

模型表单:

class MessageTemplateForm(forms.ModelForm):
    network_messages = NetworkMessageChoiceField(queryset=NetworkMessageTemplate.objects, 
                                             widget=forms.CheckboxSelectMultiple())        
    class Meta:
        model = UserProfile
        fields = ('network_messages',)

保存表单的视图:

def save_message_templates(request, extra_context=dict()):
    try:
        profile_obj = request.user.get_profile()
    except ObjectDoesNotExist:
        profile_obj = UserProfile(user=request.user)

    if request.method == 'POST':
        form = MessageTemplateForm(request.POST, instance=profile_obj)
        if form.is_valid():
            form.save()
            return redirect('/')

    return index(request, message_template_form=form)

编辑:

我的表单字段丢失,Required=False。

class MessageTemplateForm(forms.ModelForm):
    network_messages = NetworkMessageChoiceField(queryset=NetworkMessageTemplate.objects, 
                                                 widget=forms.CheckboxSelectMultiple(),
                                                 required=False)        
    class Meta:
        model = UserProfile
        fields = ('network_messages',)

I have a ModelForm in my Django app that uses a forms.ModelMultipleChoiceField, which displays as a forms.CheckboxSelectMultiple widget on the form. This ModelForm is used to select/de-select values for a many-to-many relation. Here's the problem: when you uncheck all of the checkboxes and save the form, it doesn't save. If you uncheck all but 1, it does save properly.

Are there any tricks I'm missing here about model forms and many-to-many relations? Am I encountering a bug? I'm new to Django. Thanks in advance.

Custom Field:

class NetworkMessageChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.display_message    

Model Form:

class MessageTemplateForm(forms.ModelForm):
    network_messages = NetworkMessageChoiceField(queryset=NetworkMessageTemplate.objects, 
                                             widget=forms.CheckboxSelectMultiple())        
    class Meta:
        model = UserProfile
        fields = ('network_messages',)

View that saves form:

def save_message_templates(request, extra_context=dict()):
    try:
        profile_obj = request.user.get_profile()
    except ObjectDoesNotExist:
        profile_obj = UserProfile(user=request.user)

    if request.method == 'POST':
        form = MessageTemplateForm(request.POST, instance=profile_obj)
        if form.is_valid():
            form.save()
            return redirect('/')

    return index(request, message_template_form=form)

Edit:

My form field was missing Required=False.

class MessageTemplateForm(forms.ModelForm):
    network_messages = NetworkMessageChoiceField(queryset=NetworkMessageTemplate.objects, 
                                                 widget=forms.CheckboxSelectMultiple(),
                                                 required=False)        
    class Meta:
        model = UserProfile
        fields = ('network_messages',)

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

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

发布评论

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

评论(1

糖粟与秋泊 2024-08-27 22:23:26

您没有粘贴模型的样子,因此我猜测模型中的 network_messages 字段是必需的。如果是这种情况,那么当您尝试提交该字段值为 NULL(空)的表单时,form.is_valid() 不会返回 < code>True 因此您的 form.save() 永远不会被执行。

您是否尝试过从交互式 shell 中执行这些内容,实例化表单并尝试手动 save() 它?

You didn't paste what your model looks like, so I am guessing that network_messages field in your model is required. If that is the case, then when you attempt to submit the form with the value of that field as NULL (empty), then form.is_valid() is not returning True and therefore your form.save() is never being executed.

Have you tried executing this stuff from an interactive shell, instantiating the form and attempting to manually save() it?

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