如何使用 Django Forms 在前端显示动态且可靠的模型字段值列表?

How do I show dynamic and dependable list of values of model field on Front End using Django Forms?

我有一个 Detail 模型,它有一个 ForeignKey()User 模型。我想在模板的前端显示与单个用户关联的 subject(这是 Detail 模型的字段)列表。它应该是一个下拉菜单,用户应该能够 select 列表中的主题并提交表单。

我该如何完成?

下面是我的models.py

class Detail(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    subject = models.CharField(max_length=50)
    skype_session_attendance = models.FloatField()
    internal_course_marks = models.FloatField()
    programming_lab_activity = models.FloatField()
    mid_term_marks = models.FloatField()
    final_term_marks = models.FloatField()

    def __str__(self):
        return f'{self.subject, (self.user.username)} Details'

下面是我的 views.py:

def performanceCalculator(request):
    if request.method == 'POST':
        performance_form = PerformanceCalculatorForm(request.POST, user=request.user)

        if performance_form.is_valid():
            sub = performance_form.cleaned_data['subject']

            detail = Detail.objects.all().filter(user=request.user, subject=sub).first()

            result = fuzz_algo(detail.skype_session_attendance,
                detail.internal_course_marks, detail.programming_lab_activity,
                detail.mid_term_marks, detail.final_term_marks)

            messages.success(request, result)

            return redirect('performance_calculator')
    else:
        performance_form = PerformanceCalculatorForm(user=request.user)

    context = {
        'performance_form': performance_form,        
    }

    return render(request, 'users/performance_calculator.html', context)

以下为forms.py:

class PerformanceCalculatorForm(forms.Form):
    subject = # what should I put here in order to make a dropdown list?

    class Meta:
        fields = ['subject']

下面是views.py中PerformanceCalculatorForm的更新代码:

class PerformanceCalculatorForm(forms.Form):
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(PerformanceCalculatorForm, self).__init__(*args, **kwargs)
        self.fields['subject'].queryset = Detail.objects.filter(user=user)

    subject = forms.ModelChoiceField(queryset=None)

    class Meta:
        fields = ['subject']

你不需要把它放在这里

class PerformanceCalculatorForm(forms.Form):
    subject = # what should I put here in order to make a dropdown list?

    class Meta:
        fields = ['subject']

https://docs.djangoproject.com/en/3.0/ref/models/fields/#choices

上有片段

相反,在您的 models.py

上进行
class Detail(models.Model):
    #create your choice tuple
    SUBJECT_CHOICES = [
        #(actual value on database, human readable text)
        ('math','Math'),
        ('algebra1', 'Algebra I'),
        ('calculus3','Calculus III'),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE)
                                              #here add the choices
    subject = models.CharField(max_length=50, choices=SUBJECT_CHOICES)
    skype_session_attendance = models.FloatField()
    internal_course_marks = models.FloatField()
    programming_lab_activity = models.FloatField()
    mid_term_marks = models.FloatField()
    final_term_marks = models.FloatField()

    def __str__(self):
        return f'{self.subject, (self.user.username)} Details'

通过将元组传递给选择值,它将在渲染中替换为 select 框。


与向模型字段动态添加选项相关的更新: 一个更好、更实用的方法是使用一个函数 returns 每个主题并将其附加到您的选择列表中。

在你的 models.py 中保持原样。

class Detail(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    subject = models.CharField(max_length=50)
    skype_session_attendance = models.FloatField()
    internal_course_marks = models.FloatField()
    programming_lab_activity = models.FloatField()
    mid_term_marks = models.FloatField()
    final_term_marks = models.FloatField()

    def __str__(self):
        return f'{self.subject, (self.user.username)} Details'

对于你评论的问题,你可以直接return把__str__改成你喜欢的,但是用特殊字符分开,然后就会在[=45=上看到] 请求并使用 split() 从查询集对象中获取 subject

在您的模型的 __str__ 处:

    return f'{self.user.username}-{self.subject}'

现在在你的 views.py 中使用 split() 到你想要匹配的部分

def performanceCalculator(request):
    if request.method == 'POST':
        performance_form = PerformanceCalculatorForm(request.POST, user=request.user)

        if performance_form.is_valid():
            sub = performance_form.cleaned_data['subject']
            sub = str(sub).split('-')[1] #user-subject will get the subject part

            detail = Detail.objects.all().filter(user=request.user, subject=sub).first()

            result = fuzz_algo(detail.skype_session_attendance,
                detail.internal_course_marks, detail.programming_lab_activity,
                detail.mid_term_marks, detail.final_term_marks)

            messages.success(request, result)

            return redirect('performance_calculator')
    else:
        performance_form = PerformanceCalculatorForm(user=request.user)

    context = {
        'performance_form': performance_form,        
    }

    return render(request, 'users/performance_calculator.html', context)