简体   繁体   中英

Django: form.as_p not showing up in rendered template

Django:
I've passed form.as_p into my html template however it doesn't show up in the browser. What am I doing wrong??

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>

I do not understand as to why {{ form.as_p }} does not work. Please help.

You need to use ModelForm to generate a form from a model in django. So your StudentForm will become

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

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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