开发者

how to use ForeignKeyRawIdWidget

开发者 https://www.devze.com 2022-12-21 15:23 出处:网络
I want to extend ForeignKeyRawIdWidget so I want to be able to use it without setting raw_id_fields. With the follwoing I don\'t get an error but I see no effect:

I want to extend ForeignKeyRawIdWidget so I want to be able to use it without setting raw_id_fields.

With the follwoing I don't get an error but I see no effect:

# models.py
class Product(models.Model):
    ...

class GroupProduct(Product):
    ...
    products = models.ManyToManyField(Product, related_name="%(class)s_related")

# forms.py
class GroupProductAdminForm(forms.ModelForm):    
    class Meta:
        model = GroupProduct
        widgets = {
            'products': ForeignKeyRawIdWidget(GroupProduct._meta.get_field('products').rel),
        }

Th开发者_C百科is gives me an error: init() takes at least 2 non-keyword arguments (1 given)

products = forms.ModelMultipleChoiceField(widget=ForeignKeyRawIdWidget(GroupProduct._meta.get_field('products').rel))

How do I do that?

Thanks


You forgot to pass the related Model-QuerySet to ModelMultipleChoiceField.

products = forms.ModelMultipleChoiceField(Product.objects, widget=ForeignKeyRawIdWidget(GroupProduct._meta.get_field('products').rel))


Using ManyToManyRawIdWidget instead of ForeignKeyRawIdWidget fixed it for me.

0

精彩评论

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