问题
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