简体   繁体   English

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

[英]Django: form.as_p not showing up in rendered template

Django: Django:
I've passed form.as_p into my html template however it doesn't show up in the browser. 我已经将form.as_p传递到我的html模板中,但是它没有显示在浏览器中。 What am I doing wrong?? 我究竟做错了什么??

models.py: models.py:

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

urls.py: urls.py:

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

forms.py: forms.py:

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

views.py: 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: studentform.html:

<form>

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

</form>

I do not understand as to why {{ form.as_p }} does not work. 对于{{form.as_p}}为什么不起作用,我不明白。 Please help. 请帮忙。

You need to use ModelForm to generate a form from a model in django. 您需要使用ModelForm从Django中的模型生成表单。 So your StudentForm will become 因此,您的StudentForm将变为

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

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM