获取模型类中"created_by"字段的当前用户 [英] get current user for 'created_by' field in model class
本文介绍了获取模型类中"created_by"字段的当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前正在使用Django应用,并且正在尝试将当前用户设置为模型的默认用户,但是它不起作用.
I'm currently working on a Django app, and I'm trying to set the current user as default on a model, but it doesn't work.
created_by = models.ForeignKey(User, default=request.user, null=True, blank=True, on_delete=models.DO_NOTHING, related_name='created_by')
我试图覆盖save()方法,但是它也不起作用,任何人对此事都有经验吗?
I tried to override the save() method but it doesn't work either, anyone has any experience on this matter ?
非常感谢您的帮助
推荐答案
请参阅官方文档.它解释得很好.还有一个例子
Refer official doc. It explained it pretty well. An example is also there
from django.views.generic.edit import CreateView
from myapp.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['name']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
这篇关于获取模型类中"created_by"字段的当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文