0

我在构建显示模型中存在的所有对象的属性(名称)的下拉列表(带有主动搜索过滤)时遇到问题(课程)。我发现select2是一个很好的选项来实现这一点,因此安装了django-select2

这是我到目前为止所拥有的,为简洁起见省略了内容。

模型.py

class Course(models.Model):
    courseID = models.CharField(max_length=6, blank="True", null="True")
    name = models.CharField(max_length=256, blank="True", null="True")
    hasProject = models.BooleanField(default=False)
    taughtBy = models.ManyToManyField(User)

网址.py

url(r'^courses/$', courses)

表格.py

from django import forms
import django_select2
from django_select2 import *
from models import Course

class CourseForm(forms.Form):  # also tried forms.ModelForm -> same results
    Title = ModelSelect2Field(widget=django_select2.Select2Widget(select2_options={
        'width': '400px',
        'placeholder': '',
    })
        , queryset=Course.objects.values_list('name', flat=True))

视图.py

def courses(request):
    if request.method == 'POST':
        form = CourseForm()
        print "Form Type:", type(form)
        print "ERRORS:", form.errors
        if form.is_valid():
            course = form.cleaned_data['Title']
            print "Course Selected:", course
        return HttpResponseRedirect('/home/')
    else:
        form = CourseForm()
        return render(request, 'templates/home/courses.html', {'form': form})

课程.html

<form method="POST" id="courseForm" action="#" style="padding-bottom: 0px; margin-bottom: 0">
    <div class="badge pull-right">Hint: You can start typing the title of the course</div>
    {% csrf_token %}
        <table>
            {{ form }}
        </table>
        <div style="padding-left: 380px; padding-top: 10px">
            <button type="submit" class="btn btn-default">Submit</button>
        </div>
</form>

问题

表单始终无效,错误为空白。表单类型为Type: <class 'coursereview.forms.CourseForm'>.

我将下拉列表显示为 aModelForm但平面列表包含对象的名称,因此我得到Type: <class 'coursereview.forms.CourseForm'>的不是 ModelForm - 所以我无法解码选择的课程并相应地显示相应的页面。

我已经看到了这个问题,并且正在考虑覆盖label_from_instance. 我在使用时遇到了麻烦django-select2。我尝试将其设置为ChoiceField,但该表单仍然因错误而无效。此外,下拉菜单看起来比 select2 的更丑。:P

class CourseForm(ModelForm):
    iquery = Course.objects.values_list('name', flat=True).distinct()
    iquery_choices = [('', 'None')] + [(id, id) for id in iquery]
    Title = forms.ChoiceField(iquery_choices,
                                required=False, widget=forms.Select())
    class Meta:
        model = Course
        exclude = ('taughtBy', 'courseID', 'name', 'hasProject')

理想情况下,我想使用ModelSelect2Field我在前面提到的 forms.py 中使用的内容,并从中返回所选课程。

4

1 回答 1

0

该错误与您使用的选择字段无关。您根本没有将 POST 数据传递给表单。

您在视图的其余部分也有一些缩进错误。整个事情应该是:

if request.method == 'POST':
    form = CourseForm(request.POST)
    if form.is_valid():
        course = form.cleaned_data['Title']
        print "Course Selected:", course
        return HttpResponseRedirect('/home/')
else:
    form = CourseForm()
return render(request, 'templates/home/courses.html', {'form': form})
于 2013-10-07T20:05:44.313 回答