如何在Django InlineFormSet中将Model属性显示为固定显示字符串?

时间:2016-05-09 08:16:06

标签: django formset

编辑:部分问题已经回答,所以这是剩下的部分

我有一个Django InlineFormSet,允许用户编辑与报告对应的多个Score对象。每个分数与指标相关联(表示正在评分的绩效领域)。

This is what the form looks like right now.

如何在“指标”下拉列表选项字段中提取初始指标选项的文本,并将其显示为“分数”选择字段的固定,不可编辑的文本标签?

我的模特和观点如下。

models.py

class Country(models.Model):
    name = models.CharField(max_length=50)

# Indicators
class Indicator(models.Model):
    target = models.ForeignKey(Target)
    number = models.CharField(max_length=5)
    # Order is an integer indicating how the areas should be sequentially ordered
    # The smallest integer should be listed first
    order = models.IntegerField(default=0)
    name = models.CharField(max_length=200)
    def __str__(self):
    if self.name:
        return self.value

# Reports
class Report(models.Model):
    author = models.ForeignKey('auth.User')
    country = models.ForeignKey(Country)
    created_date = models.DateTimeField(default=timezone.now)

# Possible numeric score choice and associated display color
class ScoreChoice(models.Model):
    value = models.IntegerField()
    name = models.CharField(max_length=50, null=True)
    color = models.CharField(max_length=10)
    description = models.TextField(blank=True, null=True)
    created_date = models.DateTimeField(default=timezone.now)
    def __str__(self):
    if self.name:
        return str(self.value)

# Actual scores, with the value as one of the score choices
# and belonging to a report and indicator
class Score(models.Model):
    value = models.ForeignKey(ScoreChoice, null=True)
    indicator = models.ForeignKey(Indicator, null=True)
    report = models.ForeignKey(Report, null=True)

views.py

def report_create(request, pk):
    indicators = Indicator.objects.order_by('order')

    # Create a new report for the country and associated report form
    report = Report(country=Country.objects.get(pk=pk), author=request.user)
    report_form = ReportForm(instance=report)

    ScoreInlineFormSet = inlineformset_factory(Report, Score, fields=('indicator', 'value'), 
    extra=len(indicators), can_delete=False)
    formset = ScoreInlineFormSet(instance=report, initial=[{'indicator': i} for i in indicators])

    if request.method == 'POST':
        report_form = ReportForm(request.POST, instance=report)
        formset = ScoreInlineFormSet(request.POST)

        if report_form.is_valid():
            created_report = report_form.save(commit=False)
            formset = ScoreInlineFormSet(request.POST, instance=created_report)

            if formset.is_valid():
                created_report.save()
                formset.save()
                return redirect('report_detail', pk=created_report.pk)

    return render(request, 'ghsanavigator/report_create.html',
     {'formset': formset, 'report_form': report_form, 'indicators': indicators, 'country': Country.objects.get(pk=pk).name})

----------

第一个已经解决的问题总结如下,供您参考(由vgrubes回答)

Currently, the form looks like this

如何更改以便下拉字段不会被" ScoreChoice Object"填充。但实际的Score.ScoreChoice.value?对于指标下拉字段也是如此。

通过执行以下操作,我能够为简单的ModelForm实现#2,但我不知道如何为InlineFormSet执行此操作!我不知道如何做#1。

class ScoreChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s" % (obj.value)

class ScoreForm(forms.ModelForm):
    value = ScoreChoiceField(queryset=ScoreChoice.objects.all())
    ...

1 个答案:

答案 0 :(得分:0)

我只能对您的问题提供部分答案。您可以在模型中指定一个 unicode 方法,该方法将返回字符串而不是模型对象实例。

class Indicator(models.Model):
    target = models.ForeignKey(Target)
    number = models.CharField(max_length=5)
    order = models.IntegerField(default=0)
    name = models.CharField(max_length=200)

    def __unicode__(self):
        if self.name:
            return self.name

这将解决您的指标对象问题。并以类似的方式修复ScoreChoice对象问题。