获取模型类中“ created_by”字段的当前用户

时间:2018-10-18 10:27:14

标签: django django-models django-users django-request

我目前正在使用Django应用,并且正在尝试将当前用户设置为模型的默认用户,但是它不起作用。

created_by = models.ForeignKey(User, default=request.user, null=True, blank=True, on_delete=models.DO_NOTHING, related_name='created_by')

我试图覆盖save()方法,但它也不起作用,任何人对此事都有经验吗?

非常感谢您的帮助

2 个答案:

答案 0 :(得分:1)

请参阅官方文档。它解释得很好。还有一个例子

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)

https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/#models-and-request-user

答案 1 :(得分:0)

如果有人遇到此问题,我会遵循a_k_v的建议并在视图中进行操作。 这是我的操作方式:

我在课堂上添加了两个字段:

class Class(models.Model):
    created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='create')
    updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='update')

然后创建了一个函数:

def created_updated(model, request):
    obj = model.objects.latest('pk')
    if obj.created_by is None:
        obj.created_by = request.user
    obj.updated_by = request.user
    obj.save()

使其进入我的views.py:

    if request.method == 'POST':
    form = AddVacation(request.POST)
    if form.is_valid:
        form.save()
        created_updated(Vacation, request)