如何在Django管理网站中编辑下拉菜单 [英] How to edit the dropdown in the django admin site

查看:275
本文介绍了如何在Django管理网站中编辑下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有三个类,如下所示。
当我输入表4的数据时,当我输入主题名称时,我只希望问题字段的下拉列表中包含所选主题的问题。
有没有办法做到这一点?
另外,在我的admin.py中,我仅注册了表。

So I have three classes as shown below. When I'm entering the data for table4, when I enter the topic name, I want only questions of that chosen topic to come in the dropdown for the question field. Is there any way to do this? Also, in my admin.py, I have only registered the tables.

class table5(models.Model):
    topic_name=models.CharField(max_length=222,primary_key=True)

    def __str__(self):
        return self.topic_name


class table3(models.Model):
    id1=models.IntegerField(default=0)
    topic=models.ForeignKey(table5, related_name='topic1',on_delete=models.CASCADE)
    question=models.CharField(max_length=222,primary_key=True)
    answer=models.CharField(max_length=222)

    def __str__(self):
          return self.question

class table4(models.Model):
    username = models.CharField(max_length=222,primary_key=True)
    topic=models.ForeignKey(table5, related_name='topic111',on_delete=models.CASCADE)
    question1=models.ForeignKey(table3, related_name='question3',on_delete=models.CASCADE)
    answer = models.CharField(max_length=222)

    def __str__(self):
       return self.username


推荐答案

您只需要两个覆盖即可。

You just need two overrides to do so.

首先创建两个类,然后返回要在外键选项中显示的所需文本。

First create two classes and return the desired text you want to be displayed in the foreign key option.

class QuestionChoiceField(forms.ModelChoiceField):
     def label_from_instance(self, obj):
         return "Question: {}".format(obj.question)

class TopicChoiceField(forms.ModelChoiceField):
     def label_from_instance(self, obj):
         return "Topic: {}".format(obj.topic)

现在在以下模型的管理中添加以下功能。

Now in the admin of the following model add the following function.


class QuestionAnswerAdmin(admin.ModelAdmin):



    def formfield_for_foreignkey(self, db_field, request, **kwargs):
       if db_field.name == 'question':
          return QuestionChoiceField(queryset=Table3.objects.all())
       if db_field.name == 'topic':
          return TopicChoiceField(queryset=Table3.objects.all())
    return super().formfield_for_foreignkey(db_field, request, **kwargs)



admin.site.register(table4, QuestionAnswerAdmin)

这篇关于如何在Django管理网站中编辑下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆