3

我正在编写一个应用程序django1.4来显示Lessons 和 s我Course想给出一个用户可以选择的edit_lesson视图。Course当显示编辑页面时,与课程关联的课程应显示为默认选择。

我试着写这样的视图

def get_form_data(request):
    return request.POST if request.method == 'POST' else None

def edit_lesson(request,id,template_name):
   lesson = get_object_or_404(Lesson,pk=id,author=request.user)
   form_data = get_form_data(request)
   course_choices_form = CourseChoicesForm(form_data)
   ...
   context = {'course_choices_form':course_choices_form,...}
   if request.method == 'POST' and ....:
       ...

   #if GET method ,display the form with initial data
   course_choices_form = CourseChoicesForm(initial={'courseoption':lesson.course})
   context.update({'course_choices_form':course_choices_form})
   print "context['course_choices_form'].initial=",context['course_choices_form'].initial
   return custom_render(request,context,template_name)

CourseChoicesForm 就像

class CourseChoicesForm(forms.Form):
    courseoption = forms.ChoiceField(choices=[],required=False,label='Course')
    def __init__(self, *args, **kwargs):
        super(CourseChoicesForm, self).__init__(*args, **kwargs)
        self.fields['courseoption'].choices = [(x.id,x.title) for x in Course.objects.all()]

在 edit_lesson 模板中,我将 course_choices_form 显示为

{{ course_choices_form.as_p}}

尽管如此,下拉列表并没有显示课程的课程,而只是 Course.objects.all() 中的第一个条目。

有人可以告诉我我做错了什么吗?

4

1 回答 1

3

这就是我正在做的事情:

class CourseChoicesForm(forms.ModelForm):
     courseoption = forms.ModelChoiceField(Courses.objects.all())

Django 引擎会为您制作元组列表以填充 ChoiceField。Courses.objects.all()可以是任何查询集。

https://docs.djangoproject.com/en/dev/ref/forms/fields/#fields-which-handle-relationships

于 2012-09-23T10:12:49.783 回答