63π
Use the render_change_form
method:
class CompanyAdmin(admin.ModelAdmin):
def render_change_form(self, request, context, *args, **kwargs):
context['adminform'].form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
return super(CompanyAdmin, self).render_change_form(request, context, *args, **kwargs)
68π
I actually prefer to do it in get_form
like so:
Django < 2:
class CompanyAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(CompanyAdmin, self).get_form(request, obj, **kwargs)
form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
return form
Django >= 2
class CompanyAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super(CompanyAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
return form
- [Django]-Change a form value before validation in Django form
- [Django]-What is reverse()?
- [Django]-Sending images using Http Post
25π
look here http://books.agiliq.com/projects/django-admin-cookbook/en/latest/filter_fk_dropdown.html
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "category":
kwargs["queryset"] = Category.objects.filter(name__in=['God', 'Demi God'])
return super().formfield_for_foreignkey(db_field, request, **kwargs)
- [Django]-Get virtualenv's bin folder path from script
- [Django]-Inject errors into already validated form?
- [Django]-What should I use instead of syncdb in Django 1.9?
6π
In Django 3 it is easy :
class CompanyAdmin(admin.ModelAdmin):
list_display = ('name','theme')
list_filter = ('theme__name',)
admin.site.register(Company,CompanyAdmin)
This will show you a filter on the right of your screen with the list of your themeβs name.
- [Django]-Django 1.8 KeyError: 'manager' on relationship
- [Django]-Saving ModelForm error(User_Message could not be created because the data didn't validate)
- [Django]-Django dynamic forms β on-the-fly field population?
4π
Another option is to create a custom model form where the queryset attribute of the theme
field will be fine tuned to meet your needs.
class CompanyForm(ModelForm):
class Meta:
model = CompanyForm
fields = __all__ # or a tuple of fields
def __init__(self, *args, **kwargs):
super(CompanyForm, self).__init__(*args, **kwargs)
if self.instance: # Editing and existing instance
self.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
This model form can be also reused outside of the django admin area.
- [Django]-Django 1.7 β "No migrations to apply" when run migrate after makemigrations
- [Django]-Split models.py into several files
- [Django]-Cannot import name patterns
2π
I faced with the need to add filter to the foreignKey queryset of the parent ModelAdmin class (which all other ModelAdmins inherit from), that is, I canβt know exactly which model I need, this is my solution: db_field.related_model.objects.filter()
class TSModelAdmin(admin.ModelAdmin):
exclude = ('site',)
...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.related_model:
kwargs["queryset"] =
db_field.related_model.objects.filter(site=request.user.user_profile.site)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
used django version 2.2.10
- [Django]-Unique BooleanField value in Django?
- [Django]-What is the use of PYTHONUNBUFFERED in docker file?
- [Django]-How to add clickable links to a field in Django admin?
0π
A bit unrelated, but similar to this so Iβll post this here.
I was looking for a way to remove the NULL choice selection on a ModelForm foreignkey field. I first thought I could filter the queryset as is done in other answers here, but that didnβt work.
I found that I can filter the entry where the pk value is NULL like this in the get_form
method:
class CompanyAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
# remove null choice
form.base_fields["theme"].choices = ((pk, display) for pk, display in form.base_fields["theme"].choices if pk)
return form
- [Django]-Django β "no module named django.core.management"
- [Django]-Format numbers in django templates
- [Django]-Heroku, postgreSQL, django, comments, tastypie: No operator matches the given name and argument type(s). You might need to add explicit type casts