关于 Django 在我的模型中访问和保存用户外键的问题
我看到类似的问题已经被问过但我想知道是否有更简单的方法来实现这一目标。
还关注了这篇博文。
下面给出了一个示例模型。
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() 之前是否可以将当前登录的用户发送到模型?
视图中:
if request.method == 'POST':
if not errors:
f = PostForm(request.POST)
f.save()
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.
Also followed this blog post.
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()
Isn't it possible to send current logged in user to the Model before calling save()?
In the view:
if request.method == 'POST':
if not errors:
f = PostForm(request.POST)
f.save()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
鉴于您已使用 django-admin 对其进行了标记,我假设您希望保存通过管理界面修改对象的用户。 (您实际上无法在模型的 save 方法中执行此操作,因为它不一定有权访问
User
对象 - 例如,如果您从 shell 接口保存对象怎么办?)要在 Django 管理中执行此操作,只需覆盖
ModelAdmin
的save_model
方法:当然,您需要实际添加一个名为
ForeignKey
code>user 到您的模型才能正常工作...Given that you've tagged this with
django-admin
, I'll assume you're wishing to save theUser
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 aUser
object -- e.g. what if you're saving an object from a shell interface?)To do this within Django's admin, simply override the
save_model
method of yourModelAdmin
:Of course, you would need to actually add a
ForeignKey
nameduser
to your model for that to work...