我正在编写一个应用程序django1.4
来显示Lesson
s 和 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() 中的第一个条目。
有人可以告诉我我做错了什么吗?