ModelForm没有出现在Django模板中?

时间:2013-08-02 07:07:22

标签: django models django-forms

模型

class VideoInfo(models.Model):
    user = models.ForeignKey(User)
    video_name = models.CharField(max_length=200)
    director = models.CharField(max_length=200)
    cameraman = models.CharField(max_length=200)
    editor = models.CharField(max_length=200)
    reporter = models.CharField(max_length=200)
    tag = models.TextField()   

的形式

class LoginForm(forms.Form):
    username = forms.CharField(max_length=50)
    password = forms.CharField(widget=PasswordInput())


class VideoInfoForm(forms.Form):

     class Meta:
         model = VideoInfo
         fields = ['video_type', 'director', 'cameraman', 'editor', 'reporter', 'tag']

查看:

class Main(View):
    '''Index page of application'''
    def get(self, request):
        model = VideoInfo
        form = VideoInfoForm()
        return render_to_response('main.html', {'form':form}, context_instance=RequestContext(request))

在模板中调用:

{{form.as_p}}

表单没有显示,但如果我使用LoginForm它就会显示出来。我做错了什么?

2 个答案:

答案 0 :(得分:2)

变化:

class VideoInfoForm(forms.Form):

要:

class VideoInfoForm(forms.ModelForm):

答案 1 :(得分:1)

由于您想使用模型表单,因此您对表单的定义不正确。

更改

class VideoInfoForm(forms.Form):

class VideoInfoForm(forms.ModelForm):
#       ------------------^ use ModelForm not Form

旁注:

而不是fields使用exclude的长列表,而只列出不需要的字段。

class VideoInfoForm(forms.ModelForm):
    class Meta:
        model = VideoInfo
        exclude = ['user',]