0
我正在使用django admin tabular-inline管理界面。django admin表格行限制外鍵選擇字段
model.py
class Issues(TimeStampedModel):
issue_owner = models.ForeignKey(USER_MODEL, related_name='issue_owner')
issue_no = models.CharField(max_length = 500, null = True, blank = True)
class IssueComments(TimeStampedModel):
comment_owner = models.ForeignKey(USER_MODEL, related_name='comment_owner')
issue = models.ForeignKey(Issues, null=True, blank=True)
comment = models.TextField(null=True, blank=True)
我試圖用表格內聯在管理
admin.py
class IssueCommentsAdmin(admin.TabularInline):
model = IssueComments
extra = 1
def formfield_for_foreignkey(self, db_field, request=None,**kwargs):
field = super(IssueCommentsAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'comment_owner':
if request.user is not None:
field.queryset = field.queryset.filter(username = request.user.username)
if not field.queryset:
field.queryset = field.queryset.all()
else:
field.queryset = field.queryset.none()
return field
class IssuesAdmin(admin.ModelAdmin):
model = Issues
list_display = ('issue_no', 'title', 'owner_phone_number', 'status', 'issue_priority', 'classification')
inlines = [ IssueCommentsAdmin ]
def render_change_form(self, request, context, *args, **kwargs):
context['adminform'].form.fields['assigned_to_user'].queryset = User.objects.filter(is_staff=True)
return super(IssuesAdmin, self).render_change_form(request, context, args, kwargs)
我想限制comment_owner僅在登錄的用戶選擇場。我也能夠做到這一點,但我面臨的問題是對已經有comment_owner的評論,我想保持原樣。 這裏有comment_owner的評論沒有被預選。
PLS顯示錯誤,謝謝 –
沒有收到任何錯誤,但是comment_owner對於已經分配了哪個評論所有者而變得空白。 – Gaurav
RU肯定: field.queryset.filter(用戶名= request.user.username) 可能: QS =超(IssueCommentsAdmin,個體經營).get_queryset(請求) 回報qs.filter(issue_owner = request.user 。ID) –