1π
β
I would advise to simply exclude the field from the form, and assign the user when you save the model with the .save_model(β¦)
methodΒ [Django-doc]:
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status', 'created_on')
list_filter = ('status',)
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
exclude = ('author',)
def get_queryset(self, request):
qs = super().get_queryset(request)
if not request.user.is_superuser:
qs = qs.filter(author=request.user)
return qs
def save_model(self, request, obj, form, change):
obj.author = request.user
return super().save_model(request, obj, form, change)
0π
Try formfield_for_foreignkey()
It overrides the default formfield for a foreign keys field. In your case, to return only current user for author
foreign key field:
class PostAdmin(admin.ModelAdmin):
...
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'author':
kwargs['queryset'] = User.objects.filter(id=request.user.id)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
π€weAreStarsDust
- [Answered ]-Which server did I use,when I configure django admin tool after typing "python manage.py runserver"?
- [Answered ]-Django check admin inline values
Source:stackexchange.com