从forms.py访问Django模型

时间:2015-12-14 10:06:42

标签: django django-models django-forms

我有一个学生模型,我想在forms.py上的选择器元素中显示所有学生。

GetPieceOutturnFileName

要获取student_name_list,我将访问views.py中的数据库:

from django import forms
from student.views import *

class selector(forms.Form):

    Selector_student = forms.MultipleChoiceField(
        required=True,
        widget=forms.Select({'class': 'form-control'}),
        choices= student_name_list
    )

我的template.html是:

def student_view(request):
     current_user_id = request.user.id
     student_name = Student.objects.filter(user_id = current_user_id).values('name');

         if request.method == 'POST':
             form = Selector(request.POST)
             if form.is_valid():
                Student_name = form.get('Student_name')
             return redirect(reverse('success'))

         else:
              form = Selector()
         return render(request, 'heroconfigurer/heroconfigurer.html',
              {'student_name_list': student_name, 'form': form})

1 个答案:

答案 0 :(得分:1)

我不确定您在视图中声明的student_name变量正在做什么,但如果您打算显示相同的选项,则需要在表单中执行相同的查询,或者你需要将一些额外的信息传递给你的表格。

我愿意:

from django import forms

class SelectorForm(forms.Form):

    def __init__(*self, *args, **kwargs):
        student_choices = kwargs.pop('student_choices')
        super(SelectorForm, self).__init__(*args, **kwargs)

        self.fields['student'] = forms.MultipleChoiceField(
            widget=forms.Select({'class': 'form-control'}),
            choices=student_choices
        )
这样你可以在视图中获得student_choices一次,然后将它们传递给表单:

def student_view(request):
    students = Student.objects.filter(user_id=request.user.id).values_list(
        'name', flat=True)
    student_form = StudentForm(request.POST or None, student_choices=students)

    if request.method == 'POST' and student_form.is_valid():
        student_name = student_form.cleaned_data.get('student')
        redirect(reverse('success'))

    return render(request, 'your-template.html',
        {'students': students, 'student_form': student_form})

从侧面说明,您确实需要在Python类上使用正确的大小写,始终应该是标题大小写。否则,您将很难区分实例和定义或类别,更不用说函数名称,变量等。