5👍
Your formfield_for_foreignkey
looks like it might be a good direction, but you have to realize that the ModelAdmin (self
) won’t give you a specific instance. You’ll have to derive that from the request
(possibly a combination of django.core.urlresolvers.resolve
and request.path
)
If you only want this functionality in the admin (and not model validation in general), you can use a custom form with the model admin class:
forms.py:
from django import forms
from models import location_unit, location, project_unit
class LocationUnitForm(forms.ModelForm):
class Meta:
model = location_unit
def __init__(self, *args, **kwargs):
inst = kwargs.get('instance')
super(LocationUnitForm, self).__init__(*args, **kwargs)
if inst:
self.fields['location'].queryset = location.objects.filter(project=inst.project)
self.fields['unit'].queryset = project_unit.objects.filter(project=inst.project)
admin.py:
from django.contrib import admin
from models import location_unit
from forms import LocationUnitForm
class LocationUnitAdmin(admin.ModelAdmin):
form = LocationUnitForm
admin.site.register(location_unit, LocationUnitAdmin)
(Just wrote these on the fly with no testing, so no guarantee they’ll work, but it should be close.)
- Django heroku static dir
- Django signals, how to use "instance"
- Django – Deployment for a newbie
- Pycharm remote project with virtualenv
Source:stackexchange.com