将当前用户存储在django模型的字段中 [英] Store the current user in a field of a django model

查看:173
本文介绍了将当前用户存储在django模型的字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到创建对象的用户的存储方式,并且我想自动执行。我找到了一些东西,但没有什么对我有用。以下是代码:

I'm trying to find the way of store the user who creates an object and I want to do it automatically. I've found some things but nothing works for me. Here is the code:

Models.py:

Models.py:

class Track(models.Model):
    ...
    usuari = models.ForeignKey(User)

Forms.py:

class TrackForm(forms.ModelForm):   
    class Meta:
        model = Track

Views.py

def pujar_track(request):
if request.method=='POST':
    formulari = TrackForm(request.POST, request.FILES)
    if formulari.is_valid():                    
        formulari.save()                    
        return HttpResponseRedirect('/inici')
else:
    formulari = TrackForm()

return render(request,'principal/trackForm.html',
    {'formulari':formulari})

我看过put:

usuari = models.ForeignKey(User, blank=True, editable=False) but

但是我不知道什么时候可以在该字段中设置用户。

But I don't know when can I set the user in the field.

感谢您的建议!

推荐答案

您可以隐藏 usuari 从您的 TrackForm ,所以用户不能选择它:

You can hide usuari from your TrackForm, so the user can't select it:

class TrackForm(forms.ModelForm):   
    class Meta:
        model = Track
        exclude = ('usuari',)

然后,用 formulari.save()替换为:

track = formulari.save(commit=False)
track.user = request.user
track.save()

这是一个常见的用例,在Django docs

This is a common use case and detailed in the Django docs.

这篇关于将当前用户存储在django模型的字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆