Question about Django Accessing and saving User Foriegnkey in my model

泪湿孤枕 提交于 2020-01-17 03:02:11

问题


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()

回答1:


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?)

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)

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



来源:https://stackoverflow.com/questions/5294504/question-about-django-accessing-and-saving-user-foriegnkey-in-my-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!