I need to get the current user logged in the save method for one of my models, just like the request.user
from the views but in the save model method, is this posible? and if it is, how can I do it?
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug.
Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.
To save data in Django, you normally use . save() on a model instance. However the ORM also provides a . update() method on queryset objects.
if you have model like this in your models.py:
class Post(models.Model):
title = models.CharField(max_length=100)
created_by = models.ForeignKey(User, editable=False)
Then in your admin.py it should be:
class PostAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.created_by = request.user
obj.save()
admin.site.register(Post, PostAdmin);
You can also remove the editable=False
if you want to allow the user to assign the created_by
to another user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With