django modelAdmin与不同的TabInline类

时间:2017-06-13 23:20:55

标签: django-models django-modeladmin

我一直在接收Django一两个月,并且没有很好的编程教育,所以请耐心等待。它可能比我找到它更容易。

我的项目是使用各种不同的问题类型从教程中扩展民意调查应用程序。每种问题类型都有不同的答案字段和选项。根据Answer_Type设置,我想显示(或不显示)模型中的相关内联。我找到了how to overload 'add' and 'change' views in ModelAdmin

class Question(models.Model):  
ANSWER_TYPE_CHOICES = (
        ('CH', 'Choice'),
        ('SA', 'Short Answer'),
        ('LA', 'Long Answer'),
        ('E3', 'Expert Judgement of Probabilities'),
        ('E4', 'Expert Judgment of Values'),
        ('RR', 'Risk Rating'),
        )
answer_type = models.CharField(max_length = 2, 
                               choices= ANSWER_TYPE_CHOICES,
                               default='SA')
question_text = models.CharField(max_length=200, default = "nil")
max_entries = models.IntegerField(default = 1)
man_index = models.IntegerField(default = 0)

和(2个例子 - 第一个不需要内联,第二个需要,允许每个问题定义风险评级):

    class Long_Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default = 1)
    long_answer = models.CharField(max_length=2000)
    def __str__(self):
        return self.long_answer

class Estimated_risk(models.Model):
# This is for those situations where the aggregate estimate is expected to be a more reliable expert judgment than the paramaterised (prob, cons) estimate.
# Risk value (a number) would be a real-world expected value of losses, for example
# It would be appropriate for a question to have risk and confidence
risk_value = models.DecimalField(max_digits = 4, decimal_places = 3)
risk_definition = models.CharField(max_length = 250)
risk_short_name = models.CharField(max_length = 10)

我写的admin.py课程意识到我不知道如何解决这个问题(这不起作用,但希望能传达我希望会发生的事情):

`class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
    ('Question', {'fields': ['question_text']}),
    ('Type', {'fields': ['answer_type'], 'classes': ['collapse']}),
    ('Maximum Answers per User', {'fields': ['max_entries']}),
    ('Presentation order (unique)', {'fields': ['man_index']}),
    ]

inlines =()
def set_inlines(self, request, object_id, form_url='', extra_context = None):
    if self.fieldsets['Type'] == 'CH':
        return [ChoiceInline]
    if self.fieldsets['Type'] == 'SA':
        return None
    if self.fieldsets['Type'] == 'LA':
        return None
    if self.fieldsets['Type'] == 'E3':
        return None
    if self.fieldsets['Type'] == 'E4':
        return None
    if  self.fieldsets['Type'] == 'RR':
        return [RiskInline]                        

inlines = set_inlines(self)`

0 个答案:

没有答案