Reputation: 11
If I create a new model which is a ForeignKey of another, can I update existing instances of "another" to have the new ForeignKeys as I create them? i.e. without going through the individual edit page of each instance of "another"?
Suppose that I have a Car model, and I create a bunch of Car instances filling their details in the django admin:
# models.py
from django.db import models
class Car(models.Model):
make = models.CharField(max_length=200)
model = models.CharField(max_length=200)
color = models.CharField(max_length=200)
...
After a year I decide to start renting cars to customers:
# models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=200)
...
class Car(models.Model):
make = models.CharField(max_length=200)
model = models.CharField(max_length=200)
color = models.CharField(max_length=200)
rented_to = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
...
If I register Customer in the admin site, I can add new customers, edit their attributes and, using inlines, add new cars that are rented to that customer:
#admin.py
from django.contrib import admin
from .models import Car, Customer
class CarInline(admin.StackedInline):
model = Car
extra = 3
class CustomerAdmin(admin.ModelAdmin):
inlines = [CarInline]
admin.site.register(Customer, CustomerAdmin)
Is there a way to add existing Car instances to a Customer from the Customer admin page, instead of clicking through all the cars and selecting their customers?
I would like to have a ModelMultipleChoiceField with all the car instances when I edit/add a new Customer, or something like the filter_horizontal functionality in M2M fields.
Upvotes: 1
Views: 870
Reputation: 2483
You can create custom form displayed in the view of Customer in django-admin.
defined by that:
admin.py
from django import forms
...
class CustomerModelForm(forms.ModelForm):
class Meta:
model = Customer
exclude = ('',)
some_other_field = forms.ChoiceField( ... )
# override save method to work as expected
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ('fields_you_want_to_display', )
form = CustomerModelForm
And then create the functionality of multiple choice field in the used form and override save methods and it would work. You can modify admin pages as you wish.
https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#adding-custom-validation-to-the-admin
Upvotes: 1