Home > Blockchain >  In Django Models, At Admin Area, how to auto assign the 'requesting' user to one of the fo
In Django Models, At Admin Area, how to auto assign the 'requesting' user to one of the fo

Time:11-03

In the following mode in my project, I want to assign the author variable of class upon the creation of model, on user end this could be done via request.user but as the class can be only instantiated from the admin area, this doesn't work.

class Blog(models.Model):
 title  =  models.CharField(max_length=300)
 content = RichTextField()

 author =  models.ForeignKey(User, related_name="Author", auto_created= True, on_delete= 
 models.CASCADE)
 date =  models.DateTimeField(auto_now_add= True)

CodePudding user response:

The auto_created=… field [Django-doc] is about model inheritance, it does not add the logged in user: the model layer is request unaware, and there is not per se a "logged in user". You thus remodel this to:

from django.conf import settings
from django.db import models


class Blog(models.Model):
    title = models.CharField(max_length=300)
    content = RichTextField()
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='blogs',
        on_delete=models.CASCADE,
        editable=False,
    )
    date = models.DateTimeField(auto_now_add=True)

In the model admin for the Blog model, you can work with:

from django.contrib import admin


@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    # …
    def save_model(self, request, obj, form, change):
        obj.author = request.user
        return super().save_model(request, obj, form, change)

Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the Blog model to the User model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the Author relation to blogs.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related