我正在一个Django(4.0 +)项目上工作,我有一个名为Post
的模型,其中我们有一个foreignkey字段作为Author
,is_staff
和Authors
组的用户可以从admin创建Post
的对象。
现在的问题是当用户单击Add Post
作为Author
字段时,它应该只显示当前用户而不是其他用户。
这是我尝试过的:
Frommodels.py
:
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
thumbnail = models.ImageField()
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='category')
featured = models.BooleanField()
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
Fromadmin.py
:
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'status','created_on')
list_filter = ("status",)
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(author=request.user)
我怎么才能做到呢?
我建议简单地从表单中排除字段,并在使用.save_model(…)
保存模型时分配用户方法<一口>[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)
Try formfield_for_foreignkey()
它覆盖了外键字段的默认表单字段。在您的示例中,只返回author
外键字段的当前用户:
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)