3

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),
        }

This 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

2 Answers 2

1

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

products = forms.ModelMultipleChoiceField(Product.objects, widget=ForeignKeyRawIdWidget(GroupProduct._meta.get_field('products').rel))
2
  • The missing objects was a typo. I had to use ManyToManyRawIdWidget instead of ForeignKeyRawIdWidget
    – pablo
    Feb 27, 2010 at 1:04
  • 2
    Commenting to note that Django 2.0 deprecated Field.rel in favor of Field.remote_field. See: stackoverflow.com/a/13917678/98187 Sep 7, 2019 at 14:41
0

Using ManyToManyRawIdWidget instead of ForeignKeyRawIdWidget fixed it for me.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.