在django管理员中创建对象时如何自动插入当前用户? [英] How to auto insert the current user when creating an object in django admin?
本文介绍了在django管理员中创建对象时如何自动插入当前用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件的数据库,一个
submitter = models.ForeignKey(User,editable = False)
其中用户
导入如下:
当特定用户提交文章时,我想自动将当前活动用户插入到提交者字段。
任何人都有任何建议?
解决方案
寻找答案,这里是我在这里找到的解决方案:
http://demongin.org / blog / 806 /
总结:
他有一个散文表如下:
$ b $导入用户
class Essay(models.Model):
title = models.CharField(max_length = 666)
body = models.TextField()
author = models.ForeignKey(User,null = True,blank = True)
多用户可以创建论文,所以他创建了一个admin.ModelAdmin类,如下所示:
from myapplication.essay.models import Essay
from django.contrib import admin
class EssayAdmin(admin.ModelAdmin):
list_display =('title','作者')
fieldsets = [
(无,{'fields': [('title','body')]}),
]
def save_model(self,request,obj,form,change):
if getattr(obj, 'author',None)为无:
obj.author = request.user
obj.save()
I have a database of articles with a
submitter = models.ForeignKey(User, editable=False)
Where User
is imported as follows:
from django.contrib.auth.models import User.
I would like to auto insert the current active user to the submitter field when a particular user submits the article.
Anyone have any suggestions?
解决方案
Just in case anyone is looking for an answer, here is the solution i've found here: http://demongin.org/blog/806/
To summarize: He had an Essay table as follows:
from django.contrib.auth.models import User
class Essay(models.Model):
title = models.CharField(max_length=666)
body = models.TextField()
author = models.ForeignKey(User, null=True, blank=True)
where multiuser can create essays, so he created a admin.ModelAdmin class as follows:
from myapplication.essay.models import Essay
from django.contrib import admin
class EssayAdmin(admin.ModelAdmin):
list_display = ('title', 'author')
fieldsets = [
(None, { 'fields': [('title','body')] } ),
]
def save_model(self, request, obj, form, change):
if getattr(obj, 'author', None) is None:
obj.author = request.user
obj.save()
这篇关于在django管理员中创建对象时如何自动插入当前用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文