Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How do I recreate or import the django admin green plus sign for adding new related instances?

Tags:

django

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!

like image 292
Experiment 626 Avatar asked Oct 15 '25 16:10

Experiment 626


2 Answers

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

like image 185
Scott Avatar answered Oct 18 '25 06:10

Scott


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.

like image 36
okm Avatar answered Oct 18 '25 06:10

okm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!