在 django auth 中重新排序用户 [英] Reorder users in django auth

查看:18
本文介绍了在 django auth 中重新排序用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,它在 django.contrib.auth 中有一个内置用户模型的 ForeignKey,我对管理员中的选择框总是按用户的排序的事实感到沮丧主键.

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 by the user's primary key.

我更愿意让它按用户名的字母顺序排序,虽然我的本能不想摆弄 Django 的内部,但我似乎找不到更简单的方法来重新排序用户.

I'd much rather have it sort by username alphabetically, and while it's my instinct not to want to fiddle with the innards of Django, I can't seem to find a simpler way to reorder the users.

我能想到的最直接的方法是进入我的 Django 安装并添加

The most straightforward way I can think of would be to dip into my Django install and add

ordering = ('username',)

到 User 模型的 Meta 类.

to the Meta class of the User model.

是否有某种我可以做的猴子补丁或任何其他侵入性较小的方法来修改用户模型的顺序?

Is there some kind of monkeypatching that I could do or any other less invasive way to modify the ordering of the User model?

或者,任何人都可以通过进行此更改来破坏任何东西吗?

Alternatively, can anyone thing of anything that could break by making this change?

推荐答案

有一种方法使用 ModelAdmin objects 来指定您自己的表单.通过指定您自己的表单,您可以完全控制表单的组成和验证.

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.

假设与User有FK的模型是Foo.

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

您的 myapp/models.py 可能如下所示:

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()

然后,您将创建一个 myapp/admin.py 文件,其中包含如下内容:

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)

完成此操作后,<select> 下拉菜单将根据用户名对用户对象进行排序.无需担心 Foo 上的其他字段...您只需要在 FooAdminForm 类中指定覆盖.不幸的是,您需要为每个模型提供此自定义表单定义,该模型具有您希望在管理站点中显示的用户 FK.

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.

这篇关于在 django auth 中重新排序用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆