使模型中的用户默认为当前用户

发布于 2024-10-12 06:35:43 字数 284 浏览 1 评论 0原文

我有以下问题:

from django.contrib.auth.models import User

class ClientDetails(models.Model):
    created_by = models.ForeignKey(User)
    ...

如何将 created_by 默认为当前登录的用户?

(我想这样做,主要是因为我可以将其隐藏在管理视图中,但也因为当我保存实例时,我不想每次都填充它)

I have the following:

from django.contrib.auth.models import User

class ClientDetails(models.Model):
    created_by = models.ForeignKey(User)
    ...

How do I make created_by default to the currently logged in user?

(I want to do this so I can hide it in the admin view mainly but also because when I save an instance I don't want to be filling it every time)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

赤濁 2024-10-19 06:35:43

由于您需要从 request 对象获取当前登录的用户,因此您无法在模型的 save 方法中获取它,但您可以覆盖模型管理员的 save_model-方法:

class MyAdmin(admin.ModelAdmin):
    def save_model(self, request, instance, form, change):
        user = request.user 
        instance = form.save(commit=False)
        if not change or not instance.created_by:
            instance.created_by = user
        instance.modified_by = user
        instance.save()
        form.save_m2m()
        return instance

Since you need to get the currently logged in user from a request object you cannot get it in the model's save-method,but you can eg override the model admin's save_model-method:

class MyAdmin(admin.ModelAdmin):
    def save_model(self, request, instance, form, change):
        user = request.user 
        instance = form.save(commit=False)
        if not change or not instance.created_by:
            instance.created_by = user
        instance.modified_by = user
        instance.save()
        form.save_m2m()
        return instance
又爬满兰若 2024-10-19 06:35:43

您必须重写 admin.py 中模型 Admin 类中的 get_changeform_initial_data 方法,如下所示:

# admin.py

class ClientDetailsAdmin(admin.ModelAdmin):
    def get_changeform_initial_data(self, request):
        get_data = super(ClientDetailsAdmin, self).get_changeform_initial_data(request)
        get_data['created_by'] = request.user.pk
        return get_data

admin.site.register(ClientDetails, ClientDetailsAdmin)

通过这种方式,您可以获得自 created_by 以来最优雅的解决方案> 当您创建新记录时,字段会被归档。

You have to override get_changeform_initial_data method in your model Admin class in admin.py as follows:

# admin.py

class ClientDetailsAdmin(admin.ModelAdmin):
    def get_changeform_initial_data(self, request):
        get_data = super(ClientDetailsAdmin, self).get_changeform_initial_data(request)
        get_data['created_by'] = request.user.pk
        return get_data

admin.site.register(ClientDetails, ClientDetailsAdmin)

In such way you obtain the most elegant solution since the created_by field is filed up when you create new record.

血之狂魔 2024-10-19 06:35:43

我最近遇到了类似的问题,这是来自我的views.py文件

def CircleAdd(request):

    form = CircleAddForm(request.POST)

    if form.is_valid():

        Circle = form.save(commit=False)
        Circle.Author = request.user
        Circle = Circle.save()

然后我有一个“圆圈”模型的表单,它实际上只是一个包装器(forms.py)

class CircleAddForm(ModelForm):
    class Meta:
        model = Circle

记住在您的视图中导入表单!

编辑:甚至不确定您是否需要单独的表单,关键位是假提交,其次是真正的提交

I had a similar issue recently, this is from my views.py file

def CircleAdd(request):

    form = CircleAddForm(request.POST)

    if form.is_valid():

        Circle = form.save(commit=False)
        Circle.Author = request.user
        Circle = Circle.save()

And then I had a form for the 'circles' model, which was just a wrapper really (forms.py)

class CircleAddForm(ModelForm):
    class Meta:
        model = Circle

Remember to import the form in your view!

Edit: not even sure if you even need to bother with the separate form, the key bit is the fake commit, followed by the real

惜醉颜 2024-10-19 06:35:43

基于已接受的答案,如果您希望使用基于类的视图执行此操作,您可以按照 docs,覆盖类视图上的 form_valid() 方法:

# views.py

from django.views.generic.edit import CreateView

class CreateClient(CreateView):
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(CreateClient, self).form_valid(form)

Building on the accepted answer, if you're looking to do this with Class Based views, you can follow the instructions in the docs, overriding the form_valid() method on the class view:

# views.py

from django.views.generic.edit import CreateView

class CreateClient(CreateView):
    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(CreateClient, self).form_valid(form)
蓝海 2024-10-19 06:35:43

普通模型字段有一个默认参数。但据我所知,ForeignKeys 没有,所以我想你需要使用 post_save 信号。

Normal modelfields have a default argument. But ForeignKeys do not as far as I know, so I guess you need to work with a post_save signal.

鼻尖触碰 2024-10-19 06:35:43

我发现:

from django.db import models
from django.contrib.auth.models import User

class CurrentUserField(models.ForeignKey):
    def __init__(self, **kwargs):
        super(CurrentUserField, self).__init__(User, null=True, **kwargs)

    def contribute_to_class(self, cls, name):
        super(CurrentUserField, self).contribute_to_class(cls, name)
        registry = registration.FieldRegistry()
        registry.add_field(cls, self)

class ClientDetails(models.Model):
    created_by = CurrentUserField()
...

来自 这里。但有没有更简单的方法呢?

I found:

from django.db import models
from django.contrib.auth.models import User

class CurrentUserField(models.ForeignKey):
    def __init__(self, **kwargs):
        super(CurrentUserField, self).__init__(User, null=True, **kwargs)

    def contribute_to_class(self, cls, name):
        super(CurrentUserField, self).contribute_to_class(cls, name)
        registry = registration.FieldRegistry()
        registry.add_field(cls, self)

class ClientDetails(models.Model):
    created_by = CurrentUserField()
...

from here. But isn't there an easier way?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文