How to auto insert the current user when creating an object in django admin?

前端 未结 5 2091
别跟我提以往
别跟我提以往 2020-12-08 01:08

I have a database of articles with a

submitter = models.ForeignKey(User, editable=False)

Where User is imported as follows: <

5条回答
  •  臣服心动
    2020-12-08 01:33

    Just in case anyone is looking for an answer, here is the solution i've found here: http://demongin.org/blog/806/

    To summarize: He had an Essay table as follows:

    from django.contrib.auth.models import User
    
    class Essay(models.Model):
        title = models.CharField(max_length=666)
        body = models.TextField()
        author = models.ForeignKey(User, null=True, blank=True)
    

    where multiuser can create essays, so he created a admin.ModelAdmin class as follows:

    from myapplication.essay.models import Essay
    from django.contrib import admin
    
    class EssayAdmin(admin.ModelAdmin):
        list_display = ('title', 'author')
        fieldsets = [
            (None, { 'fields': [('title','body')] } ),
        ]
    
        def save_model(self, request, obj, form, change):
            if getattr(obj, 'author', None) is None:
                obj.author = request.user
            obj.save()
    

提交回复
热议问题