Django ModelChoiceField does not have a plus button

I am making a Django application with user users. I have outlined the key components of my problem below, missing code is indicated by the symbol "...". My user model has a foreign key relationship as follows:

class MyCustomUser(models.AbstractBaseUser, models.PermissionsMixin) ... location = models.ForeignKey(Location) class Location(models.Model) name = models.CharField(max_length=50, blank=True, null=True) 

I wrote a custom form that includes this field as follows:

 class MyCustomUserCreationForm(models.ModelForm) ... location = forms.ModelChoiceField(Location.objects.all()) 

Everything seems to work correctly, however there is no plus button to the right of the selection field for the location. I want to be able to add location when creating a user, just as you can add polls when creating options in a Django tutorial . On this issue , I do not see a green plus if I do not have permission to change the model, but I am registered as superuser with all permissions. Any idea what I'm doing wrong?

+7
python django django-admin django-forms
source share
3 answers

You need to install the RelatedFieldWidgetWrapper wrapper in your model:

The associatedFieldWidgetWrapper (found in django.contrib.admin.widgets) is used on admin pages to enable the ability to use a foreign key to add a new related entry. (In English: places a green plus sign to the right of the control.)

 class MyCustomUserCreationForm(models.ModelForm) ... location = forms.ModelChoiceField(queryset=Location.objects.all()) def __init__(self, *args, **kwargs): super(MyCustomUserCreationForm, self).__init__(*args, **kwargs) rel = ManyToOneRel(self.instance.location.model, 'id') self.fields['location'].widget = RelatedFieldWidgetWrapper(self.fields['location'].widget, rel, self.admin_site) 

I may be wrong in the code example, so see these posts and examples:

+11
source share

I created a method based on the answers above:

 def add_related_field_wrapper(form, col_name): rel_model = form.Meta.model rel = rel_model._meta.get_field(col_name).rel form.fields[col_name].widget = RelatedFieldWidgetWrapper(form.fields[col_name].widget, rel, admin.site, can_add_related=True, can_change_related=True) 

And then calling this method from my form:

 class FeatureForm(forms.ModelForm): offer = forms.ModelChoiceField(queryset=Offer.objects.all(), required=False) package = forms.ModelChoiceField(queryset=Package.objects.all(), required=False) def __init__(self, *args, **kwargs): super(FeatureForm, self).__init__(*args, **kwargs) add_related_field_wrapper(self, 'offer') add_related_field_wrapper(self, 'package') 

This works fine on Django 1.8.2.

+6
source share

Google pointed me to this page when searching for how to get a β€œ+” sign next to fields in a custom form with ForeignKey relationships, so I thought I'd add.

For me, using django-autocomplete-light really helped, using the add more feature.

+2
source share

All Articles