0

モデル (コース) に存在するすべてのオブジェクトの属性 (名前) を表示するドロップダウン (アクティブな検索フィルタリングを使用) の作成に問題があります。select2 がこれを実装するための優れたオプションであることがわかったため、django-select2 をインストールしました。

これは私がこれまでに持っているもので、簡潔にするために内容は省略されています。

models.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)

urls.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})

course.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'>.

ドロップダウンを として表示していModelFormますが、フラット リストにはオブジェクトの名前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 に答える