开发者

How do I change the widget on a manytomany ModelForm

开发者 https://www.devze.com 2023-01-27 09:31 出处:网络
I have Book and a Category model with a manytomany relationship thru another model class Category(models.Model):

I have Book and a Category model with a manytomany relationship thru another model

class Category(models.Model):
   name = models.CharField(max_length = 255)

class Book(models.Model):
   name = models.CharField(max_length = 255)
   categories = models.ManyToManyField(Category, through='book.BookCategory')

class BookCategory(models.Model):
   business = models.ForeignKey(Business)
   category = models.ForeignKey(Category)
   user = models.ForeignKey(User)
   created = models.DateField()

Then my Forms look like this:

class BookForm(forms.ModelForm):
    name = forms.CharField(max_length = 255)
    categories = forms.ModelMultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        queryset =  Category.objects.all()
    )

    class Meta:
       开发者_JAVA技巧 model = Business
        fields = ('name', 'categories')

When I try to save an instance of the form book_form = BookForm(request.POST, instance=business) book_form.save()

I get this error: Cannot set values on a ManyToManyField which specifies an intermediary model. Use book.BookCategory's Manager instead.

How would I solve this?


As you do not have any extra fields in BookCategory, you can remove the model and the through='BookCategory' argument. Then an implicit model will be created, an you should be able to use the widget.

0

精彩评论

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