未加星标

Pretty options for Django's auth.User

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Several of my Django Apps have Foreign Key relationships to django.contrib.auth.model.User. In Django's admin app, these show up a select elements displaying the username attribute. For some people, that may be OK, but for most of the people with which I work, it's not. We want to see prettier options, i.e. each User's full name as the options in that select element.

So, here's how it works. We override the ModelChoiceField (for ForeignKeys) and the ModelMultipleChoiceField (for ManyToMany Fields):

from django.forms import ModelChoiceField, ModelMultipleChoiceField
class UserModelChoiceField(ModelChoiceField):
'''
A ModelChoiceField to represent User
select boxes in the Auto Admin
'''
def label_from_instance(self, obj):
return "%s (%s)"%(obj.get_full_name(), obj.username)
class UserModelMultipleChoiceField(ModelMultipleChoiceField):
'''
Similar to UserModelChoiceField, provide a nicer-looking
list of user names for ManyToMany Relations...
'''
def label_from_instance(self, obj):
return "%s (%s)"%(obj.get_full_name(), obj.username)

Then, to customize the admin, you need to create a custome ModelForm for your Model. So, if I had a Model that looked like this:

class MyModel(models.Model):
user = models.ForeignKey(User)

You'd need to create the following ModelForm:

class MyModelAdminForm(forms.ModelForm):
user = UserModelChoiceField(User.objects.all().order_by('first_name', 'last_name', 'username'))
class Meta:
model = MyModel

Now, when you create a ModelAdmin class for the MyModel, you specify the above form:

from models import MyModel
from forms import MyModelAdminForm
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
admin.site.register(MyModel, MyModelAdmin)

At this point, the choices for User objects in the admin should contain the user's full name and their username in parenthesis.

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: Django
分页:12
转载请注明
本文标题:Pretty options for Django's auth.User
本站链接:http://www.codesec.net/view/482052.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(26)