简体   繁体   English

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

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

I have a Detail Model which has a ForeignKey() of User Model.我有一个Detail Model,其中包含User Model 的ForeignKey() I want to show the list of subject (which is a field of Detail Model) associated with a single user, at the Front End in Template.我想在模板的前端显示与单个用户关联的subject列表(这是Detail模型的一个字段)。 It should be a dropdown menu and user should be able to select the subject from the list and submit the form.它应该是一个下拉菜单,用户应该能够从列表中选择 select 主题并提交表单。

How should I accomplish it?我应该如何完成它?

Below is my models.py下面是我的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'

and below is my views.py:以下是我的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)

and below is forms.py:以下是 forms.py:

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

    class Meta:
        fields = ['subject']

Below is the updated code of PerformanceCalculatorForm in views.py:下面是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']

You don't need to put it here你不需要把它放在这里

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

    class Meta:
        fields = ['subject']

There are snippets on https://docs.djangoproject.com/en/3.0/ref/models/fields/#choices https 上有片段://docs.djangoproject.com/en/3.0/ref/models/fields/#choices

Instead, do it on your models.py相反,在你的 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'

By passing a tuple to the choices a values, it will be replaced on the render with a select box.通过将元组传递给选择值,它将在渲染上替换为 select 框。


UPDATE related to adding choices dinamically to Model field: A better and practical way would be having a function that returns each subjects and append it to your choices list.更新与动态添加选择 Model 字段相关:更好和实用的方法是使用 function 将每个主题和 append 返回到您的选择列表。

In your models.py leave it like before.在你的 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'

For the issue that you commented, you can just return the __str__ to whatever to you like but separate it using a special character, then this will be seen on the POST request and using split() to get your subject out of the queryset object.对于您评论的问题,您可以将__str__返回到您喜欢的任何内容,但使用特殊字符将其分隔,然后这将在 POST 请求中看到,并使用split()将您的subject从查询集 object 中取出。

At the __str__ of your model:__str__的 __str__ 处:

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

now in your views.py use split() to the the part that you want to match现在在您的 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Django中使用模型字段设置动态选择字段 - How do I set a Dynamic Choice Field using a Model field in Django 对于这种特殊情况,如何在 Django 页面中的 HTML 页面中显示 model 字段值? - How do I show model field values in HTML page, in Django for this particular case? 具有动态字段值的 Django 表单 - Django Forms with dynamic field values 如何根据 Django 中的 model 字段显示导航栏项目? - How do I show navbar items based on a model field in Django? 如何使用 model forms 更新 django 中的博客文章? - How do I update blog article in django using model forms? Django:如何在文本输入字段中显示值列表? - Django: How can I show a list of values in a text input field? 如何克隆 Django 模型实例对象并在 Django 表单上显示? - How do I clone a Django model instance object and show on the Django forms? 如何使用 Django model forms(使用设置值)制作 select 字段? - How to make a select field using Django model forms (using set values)? 如何在 Django 的子 model 字段中使用抽象 model 字段值作为默认值? - How do I use abstract model field values as default values in child model fields in Django? 如何使一个字段在模型中依赖于另一个字段? Django的 - How to make one field dependable of another field in models? Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM