关于Django的问题在我的模型中访问并保存用户Foriegnkey [英] Question about Django Accessing and saving User Foriegnkey in my model

查看:172
本文介绍了关于Django的问题在我的模型中访问并保存用户Foriegnkey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到与此相似的但是我想知道是否有一个更简单的方法来实现这一点。

I see that similar to this has been asked before but I would like to know if there was a simpler way to achieve this.

还跟着本博客

下面给出了一个示例模型。

A sample Model is given below.

class Post (models.Model):
    name = models.CharField(max_length=1000, help_text="required, name of the post")
    description = models.TextField(blank=True)
    created_datetime = models.DateTimeField(auto_now_add=True, editable=False)
    modified_datetime = models.DateTimeField(auto_now=True, editable=False)
    custom_hashed_url = models.CharField(unique=True, max_length=1000, editable=False)

def save(self, *args, **kwargs):
        #How to save User here?
        super(Model, self).save()

是不是可以发送在调用save()之前,当前登录到模型的用户?

Isn't it possible to send current logged in user to the Model before calling save()?

在视图中:

if request.method == 'POST':

if not errors:

    f = PostForm(request.POST)

    f.save()


推荐答案

标记为 django-admin ,我想假设您希望保存正在修改对象的用户通过管理界面。 (您不能真正在模型的保存方法中执行此操作,因为它不一定可以访问用户对象 - 例如,如果要保存对象从shell界面?)

Given that you've tagged this with django-admin, I'll assume you're wishing to save the User who is modifying the object via the admin interface. (You can't really do it in your model's save method, because it doesn't necessarily have access to a User object -- e.g. what if you're saving an object from a shell interface?)

要在Django的管理员中执行此操作,只需覆盖 save_model c $ c> ModelAdmin :

To do this within Django's admin, simply override the save_model method of your ModelAdmin:

class PostAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        obj.save()

admin.site.register(Post, PostAdmin)

当然,您需要实际添加一个 ForeignKey 命名为用户到您的模型中工作...

Of course, you would need to actually add a ForeignKey named user to your model for that to work...

这篇关于关于Django的问题在我的模型中访问并保存用户Foriegnkey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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