简体   繁体   English

如何在 models.py 中获取当前用户?

[英]How can I get the current user in models.py?

Hi I am trying to add the User column to know which User added the tool in the tools/model.py page您好我正在尝试添加用户列以了解哪个用户在 tools/model.py 页面中添加了该工具

tools_name = models.CharField('Tool\'s Name', max_length=100, unique=True)
tools_project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True, blank=True, limit_choices_to=~Q(project_status=2), verbose_name='Project\'s Name')
user = models.CharField(max_length=100, editable=False)

But I want to know how to save the user that created or updated the tool?但我想知道如何保存创建或更新工具的用户?

Models are normally request unaware , so you should not do this.模型通常是request unaware ,所以你不应该这样做。 This is a task that belongs in the view.这是属于视图的任务。 Furthermore normally you work with a ForeignKey or a OneToOneField or another relation.此外,通常您使用ForeignKeyOneToOneField或其他关系。 This is useful since users might eventually change their (user)name.这很有用,因为用户最终可能会更改他们的(用户)名称。 By storing the username, your database can contain a username that no longer exists or even worse: another user now uses that username and the use got then access to the models of the previous "owner".通过存储用户名,您的数据库可以包含一个不再存在的用户名,甚至更糟:另一个用户现在使用该用户名,然后该用户可以访问以前“所有者”的模型。

Your model thus looks like:因此,您的 model 看起来像:

from user.conf import settings

class MyModel(models.Model):
    tools_name = models.CharField('Tool\'s Name', max_length=100, unique=True)
    tools_project = models.ForeignKey(
        Project,
        on_delete=models.DO_NOTHING,
        null=True,
        blank=True,
        limit_choices_to=~Q(project_status=2),
        verbose_name='Project\'s Name'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        editable=False
    )

You can work with a ModelForm for example and then let the view set the user:例如,您可以使用ModelForm ,然后让视图设置用户:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def my_view(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('name-of-some-view')
    else:
        form = MyModelForm()
    return render(request, 'name-of-some-template.html', {'form': form})

For the ModelAdmin you can override the .save_model(…) method [Django-doc] :对于ModelAdmin ,您可以覆盖.save_model(…)方法 [Django-doc]

from django.contrib import admin

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM