Xadmin automic field - WBowam/wbowam.github.com GitHub Wiki

Date:2014-06-16
Title:Xadmin中自动预填某个字段
Tags:Xadmin,Django
Category:It

需求:

今天写一个model时写了个字段create_by=models.ForeignKey(User)
想给它预填入当前的已登录用户。需求类似如下(当然不可能那样写):
created_by = models.ForeignKey(User, default=request.user)
如果以上需求在View里,很好解决的。可现在在AdminModel里,而且在Xadmin环境下。
于是,Google,得StackOverFlow,找到了参考资料1。感谢Google,感谢StackOverFlowx,感谢参考资料1参考资料2

解决方案

在默认的django admin环境下

models.py
#-*- coding: UTF-8 -*- 
from django.db import models
from django.contrib.auth.models import User

class Kuaijian(models.Model):
            created_by = models.ForeignKey(User)
admin.py
#-*- coding: UTF-8 -*- 
from django.contrib import admin
from models import Kuaijian

class KuaijianAdmin(admin.ModelAdmin):
        exclude = ('author',)##
###主要是如下函数的OverWrite
	def save_model(self, request, obj, form, change):
	    if not change:
	        obj.created_by = request.user
	    obj.save()

admin.site.register(Kuaijian,KuaijianAdmin)

在Xadmin的环境下

models.py跟上述的一样
adminx.py
class KuaijianAdmin(object):
        exclude = ('author',)##
###主要是如下函数的OverWrite
        def save_models(self):
		self.new_obj.created_by=self.request.user
		self.new_obj.save()
⚠️ **GitHub.com Fallback** ⚠️