How to attach current logged in user to object when object is created from django admin

筅森魡賤 提交于 2021-02-11 12:27:03

问题


I'm working on website whose an app which has class called Members whose a field that is related to the builtin User class from django.contrib.auth.models and it looks like

class Members(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    member_image = models.ImageField(upload_to='unknown')
    member_position = models.CharField(max_length=255)
    ...

So as you can see when I'm adding member_image as a user I have also to select the user which doesn't make sense to me because I want to detect which user is logged in and pass his/her id as default parameter like

class Members(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, default=request.user.id)

and after remove the user field in the admin panel like

class MembersAdmin(admin.ModelAdmin):
    fields = ('member_image', 'member_position', ...)

so that if the user field doesn't selected it will set the logged in user_id by default

but to access request out of the views.py is not possible.

so how will I achieve this I also tried the following answers

  • Access session / request information outside of views in Django
  • Accessing request.user outside views.py
  • Django: How can I get the logged user outside of view request?, etc

but still not get it


回答1:


Modify MembersAdmin save_model method and attach request.user to the object prior to saving.

class MembersAdmin(admin.ModelAdmin):
    fields = ('member_image', 'member_position', ...)
    
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        super().save_model(request, obj, form, change)



回答2:


For exclude the current logged in User for particular page or view, You can try this :-

from django.contrib.auth import get_user_model
User = user_model()

def some_view(request):
    exclude_current_user = User.objects.exclude(user=request.user)


来源:https://stackoverflow.com/questions/65847783/how-to-attach-current-logged-in-user-to-object-when-object-is-created-from-djang

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