For example I have a model like this:
class Wheel(models.Model):
wheel = models.CharField(max_length=20)
class Vehicle(models.Model):
wheel = models.ForeignKey(Wheel)
When I make a new Vehicle, I want the green plus sign to appear beside my wheel field and allow me to add new instances of Wheel. I'm quite new to django so I don't know if it's possible. Any help is appreciated!
If you are implementing your form outside the admin section, you'll need a custom widget wrapper similar to django.contrib.admin.widgets.RelatedFieldWidgetWrapper. Example on usage:
from .models import Owner
from .widgets import AddAnotherWidgetWrapper # our custom widget wrapper
class PickOwnerForm(forms.Form):
owner = forms.ModelChoiceField(
queryset=Owner.objects.all().order_by('name'),
widget=AddAnotherWidgetWrapper(forms.Select(),Owner, )
)
In your implementation, substitute 'Owner' with the model you are linking to.
You can find the custom widget wrapper along with a full example at - https://gist.github.com/ebrelsford/5263306
Check the widget django.contrib.admin.widgets.RelatedFieldWidgetWrapper
. It's the widget used by Django Admin to add the functional '+' mark, here.
In order to use the widget in your custom form, you need to provide the admin_site
argument that serves the adding page of the Wheel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With