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 theBlogmodel to theUsermodel 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 therelation toAuthorblogs.
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 theUsermodel [Django-doc] directly. For more information you can see the referencing theUsermodel section of the documentation.
