Reorder users in django auth

后端 未结 2 1949
慢半拍i
慢半拍i 2020-12-09 11:20

I have a model that has a ForeignKey to the built-in user model in django.contrib.auth and I\'m frustrated by the fact the select box in the admin always sorts

相关标签:
2条回答
  • 2020-12-09 11:53

    There is a way using ModelAdmin objects to specify your own form. By specifying your own form, you have complete control over the form's composition and validation.

    Say that the model which has an FK to User is Foo.

    Your myapp/models.py might look like this:

    from django.db import models
    from django.contrib.auth.models import User
    
    class Foo(models.Model):
        user = models.ForeignKey(User)
        some_val = models.IntegerField()
    

    You would then create a myapp/admin.py file containing something like this:

    from django.contrib.auth.models import User
    from django import forms
    from django.contrib import admin
    
    class FooAdminForm(forms.ModelForm):
        user = forms.ModelChoiceField(queryset=User.objects.order_by('username'))
    
        class Meta:
            model = Foo
    
     class FooAdmin(admin.ModelAdmin):
         form = FooAdminForm
    
     admin.site.register(Foo, FooAdmin)
    

    Once you've done this, the <select> dropdown will order the user objects according to username. No need to worry about to other fields on Foo... you only need to specify the overrides in your FooAdminForm class. Unfortunately, you'll need to provide this custom form definition for every model having an FK to User that you wish to present in the admin site.

    0 讨论(0)
  • 2020-12-09 12:15

    Jarret's answer above should actually read:

    from django.contrib.auth.models import User
    from django.contrib import admin
    from django import forms
    from yourapp.models import Foo
    
    class FooAdminForm(forms.ModelForm):
        class Meta:
            model = Foo
    
        def __init__(self, *args, **kwds):
            super(FooAdminForm, self).__init__(*args, **kwds)
            self.fields['user'].queryset = User.objects.order_by(...)
    
    class FooAdmin(admin.ModelAdmin):
        # other stuff here
        form = FooAdminForm
    
    admin.site.register(Foo, FooAdmin)
    

    so the queryset gets re-evaluated each time you create the form, as opposed to once, when the module containing the form is imported.

    0 讨论(0)
提交回复
热议问题