How to use ForeignKeyRawIdWidget

I want to extend ForeignKeyRawIdWidget so that I can use it without setting raw_id_fields.

With the following, I do not receive an error message, 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),
        }

This gives me an error: init () takes at least 2 arguments without a keyword (1 given)

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

How to do it?

thank

+3
source share
2 answers

Using ManyToManyRawIdWidget instead of ForeignKeyRawIdWidget fixed it for me.

0
source

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

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

Source: https://habr.com/ru/post/1734615/


All Articles