开发者

Populate CheckboxSelectMultiple with existing data from django model form

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

model

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 开发者_C百科categories defined in the model above. The form looks like

modelform

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.

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

Cheers


In the view maybe you can set the queryset like this:

form = BlogNotificationsForm()
form.fields["categories"].queryset = Categories.objects.all()

I found this example here


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!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜