django 显示要选择的选项值和文本

2mbi3lxu  于 2022-12-01  发布在  Go
关注(0)|答案(2)|浏览(129)

我有一个从数据库表“等级”填充的选择字段。它显示等级对象而不是“等级1”、“等级2”、“等级3”等。我如何填充选择以显示文本。

我的代码:

模型.py

class Grade(models.Model):
    grade_id = models.AutoField(primary_key=True)
    grade_name = models.CharField(max_length=10, default="")
    class Meta:
        db_table = 'grade'

class Student(models.Model):
    student_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=50, default="")
    last_name = models.CharField(max_length=50, default="")
    grade = models.ForeignKey(Grade, on_delete=models.CASCADE)
    class Meta:
        db_table = 'Student'

表单.py

class CreateStudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['grade', 'first_name', 'last_name' ]
        widgets = {
            'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}),
            'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}),
        }

查看次数.py

def student_action(request):
    form = CreateStudentForm()
    return render(request, 'student.html', {'form': form})
pod7payv

pod7payv1#

您应该在模型中定义__str__()方法,以便:

class Grade(models.Model):
    grade_id = models.AutoField(primary_key=True)
    grade_name = models.CharField(max_length=10, default="")

    def __str__(self):
        return f"{self.grade_name}"

    class Meta:
        db_table = 'grade'

如何显示选择等级而不是**- - ----**?
您可以覆写ModelForm的__init__()方法,以便:

class CreateStudentForm(forms.ModelForm):
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['grade'].empty_label = 'Select Grade'
    
    class Meta:
        model = Student
        fields = ['grade', 'first_name', 'last_name' ]
        widgets = {
            'grade': forms.Select(choices=Grade.objects.all(), attrs={'id':'selectGrade', 'class': 'form-control'}),
            'first_name': forms.TextInput(attrs={'id':'txtFirstName', 'class': 'form-control', 'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'id':'txtLastName', 'class': 'form-control', 'placeholder': 'Last Name'}),
        }
zxlwwiss

zxlwwiss2#

您需要编写str方法来表示grade_name,而不是对象名称,如下所示...
第1001章:我的models.py

class Grade(models.Model):
    grade_id = models.AutoField(primary_key=True)
    grade_name = models.CharField(max_length=10, default="")
    class Meta:
        db_table = 'grade'
    
    def __str__(self):
        return self.grade_name

相关问题