Issue
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.
Solution
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!
Answered By - devdob
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.