Django ModelMultipleChoiceField没有显示正确的选择名称

时间:2017-07-18 13:57:11

标签: python django postgresql

我正在尝试从我的postgres数据库中的视图创建多选字段,但网页显示不正确。具体来说,虽然它提供了正确数量的选择,但它并没有通过" check_name"来命名它们。字段,而是命名每个选项'检查对象'。这是我的代码:

models.py

class Check(models.Model):
    pkey = models.AutoField(primary_key=True)
    cif = models.CharField(max_length=255)
    check_name = models.CharField(max_length=255)
    description = models.TextField()

    class Meta:
        managed = False
        db_table = 'precheck_check'

forms.py

class ProcessFileForm(forms.Form):
    checks_to_run = forms.ModelMultipleChoiceField(
        queryset = Check.objects.all(),
        to_field_name = "check_name",
        widget = forms.CheckboxSelectMultiple,
        )

views.py

def successful_upload(request):
    if request.method == 'POST':
        form = ProcessFileForm(request.POST, user=request.user)
        if form.is_valid():
            return render(request, 'precheck/checks_successful.html')
    else:
        form = ProcessFileForm()
    return render(request, 'precheck/select_checks.html',{'form':form})

值得注意的是,我正从名为' precheck_check'的视图中提取数据。在postgres db中。它似乎正确地看到了视图,因为它给了我正确数量的选择。

1 个答案:

答案 0 :(得分:1)

最简单的解决方法是向Check模型添加__str__方法。

from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible  # only if you need to support Python 2
class Check(models.Model):
    pkey = models.AutoField(primary_key=True)
    cif = models.CharField(max_length=255)
    check_name = models.CharField(max_length=255)
    description = models.TextField()

    class Meta:
        managed = False
        db_table = 'precheck_check'

    def __str__(self):
        return self.check_name

如果您希望显示的值不是__str__方法的结果,则可以继承ModelMultipleChoiceField并覆盖label_from_instance

from django import forms

class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.check_name

然后使用以下格式的字段:

class ProcessFileForm(forms.Form):
    checks_to_run = forms.MyModelMultipleChoiceField(...)