Django:form.as_p未显示在呈现的模板中

时间:2019-02-02 18:04:47

标签: python django

Django:
我已经将form.as_p传递到我的html模板中,但是它没有显示在浏览器中。我在做什么错??

models.py:

class Student(models.Model):
    student_name = models.CharField(max_length=200)

urls.py:

urlpatterns = [
    path("studentform/", views.CreateStudentForm, name="CreateStudentForm"),
]

forms.py:

class StudentForm(forms.Form):
    class Meta:
        model = Student
        fields = [
            'student_name',
        ]

views.py:

def CreateStudentForm(request):
    form = StudentForm(request.POST or None)
    if form.is_valid():
        form.save()

    context = {
        'form' : form
    }

    return render(request, 'main/studentform.html', context)

studentform.html:

<form>

{{ form.as_p }}
<input type='submit' value='Save' />

</form>

我不明白为什么{{form.as_p}}无法正常工作。请帮忙。

1 个答案:

答案 0 :(得分:2)

您需要使用ModelForm从Django模型中生成表单。这样您的StudentForm就会变成

class StudentForm(forms.ModelForm):
   class Meta:
       model = Student
       fields = [
           'student_name',
       ]

希望这会有所帮助!