使用Django模型表单中的现有数据填充CheckboxSelectMultiple [英] Populate CheckboxSelectMultiple with existing data from django model form

查看:90
本文介绍了使用Django模型表单中的现有数据填充CheckboxSelectMultiple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人可以帮助我对此有所了解。我正在开发一个通知应用程序,在该应用程序中,当用户提交特定类别的IE博客文章时,用户可以注册以接收电子邮件,例如,我只希望为猫的媒体发送电子邮件并进行购买

hoping someone can help shed some light on this for me. Im working on a notifications app where users can register to recieve emails when blog posts are submitted for specific categories IE i only want emails for the cat's media and buying for example

我有一个基本模型定义为

i have a basic model defined as

class BlogNotifications(models.Model):
    
    user = models.ForeignKey(User)
    sites = models.ManyToManyField(Site)
    categories = models.ManyToManyField(Categories)
    objects = models.Manager()
    
    def __unicode__ (self):

    return self.user.username

基本上,表单应仅列出类别,即上面模型中定义的多对多字段类别。表单看起来像

basically the form should only out the categories which is the many to many field categories defined in the model above. The form looks like

class BlogNotificationsForm(forms.ModelForm):
            
    class Meta:
        model = BlogNotifications
        exclude = ('user', 'sites',)
        widgets = {
            'categories': forms.widgets.CheckboxSelectMultiple(),
        }

表单正确地将多对多字段呈现为复选框,但是我想知道的是要用现有数据填充这些复选框,即用户已经选择接收有关媒体的博客电子邮件,那么当用户导航回该页面时,购买和计划这些复选框应显示为选中状态。

the form is rendering the many to many field as Check boxes correctly but what im wondering is how to go about populating those check boxes with existing data, ie the user has already opted in to receive blog emails about media, buying and planning those check boxes should appear checked when the user navigates back to the page.

我尝试在ModelForm上定义queryset选项,但这似乎对我没有任何帮助。.非常感谢任何帮助

I have tried defining the queryset option on the ModelForm but that didn't seem to do anything for me.. Any help is greatly appreciated

干杯

推荐答案

实例化 modelForm 时,我没有传递的实例布洛gNotifications 模型。因此,在视图中,表单的设置如下所示:

When instantiating the modelForm I wasn't passing the instance of BlogNotifications model to it. So in the view the form set up looks like:

blogForm = BlogNotificationsForm(instance=BlogNotifications.objects.get(user=request.user))

我希望这会在将来对某人有所帮助,但事实并非如此在给我的文档中!

I hope this may help someone in the future, it really wasn't that clear in the docs to me!!

这篇关于使用Django模型表单中的现有数据填充CheckboxSelectMultiple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆