Django ModelForm不生成HTML表单

时间:2016-05-29 11:03:26

标签: python django

我正在尝试使用django的ModelForm类生成HTML表单。但是,它没有产生。

以下是我的文件:

models.py

from __future__ import unicode_literals

from django.db import models


class Policy(models.Model):
    policy_number = models.CharField(max_length = 9)
    province = models.CharField(max_length = 15)

    def __str__(self):
        return self.policy_number

    class Meta:
        ordering = ('policy_number',)

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views.generic import View
from .forms import *


class MyView(View):
    def get(self, request):
        #message = "Hello Sourav"
        policyForm = PolicyBaseForm(None)
        print("policyform in GET", policyForm)
        #context = {'message': message, 'policyForm': policyForm}
        return render(request, 'autoins/index.html', {'policyForm': policyForm})

    def post(self, request):
        policyForm = PolicyBaseForm(request.POST)
        print("policyform in POST", policyForm)
        if policyForm.is_valid():
            policyForm.save()
            return redirect('autoins/successPage.html')
        return HttpResponse("Error saving form data")
# def request_method(request):
#     return HttpResponse("Result")

forms.py

from django import forms
from .models import *


# class PolicyBaseForm(forms.ModelForm):
#     class Meta:
#         model = Policy
#         fields = ('policy_number', 'province')
print("in form")


class PolicyBaseForm(forms.ModelForm):
    policy_number = forms.CharField(max_length = 9, label = "Policy Number")
    province = forms.CharField(max_length = 15, label = "Province")

    class Meta:
        model = Policy
        fields = ("policy_number",)

的index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form role = "form" method = post action = "{%url 'homepage'%}">
        {%csrf_token%}
        {{policyform}}           
        <input type="submit" value="Done">
    </form>
</body>
</html>

urls.py

from django.conf.urls import url
from autoins.views import *
#from autoins import views

#from myinsurancesite.autoins.views import MyView
print('in au')
urlpatterns = [
    url(r'^home/', MyView.as_view(), name = 'homepage'),
    #url(r'^success/'MyView.as_view(), name = 'success'),
    #url(r'^home/', views.request_method, name = "request_method"),

]

我在浏览器中看到的是提交按钮,我在index.html文件中提供了表单标记。我无法看到自动生成的表单字段w.r.t模型字段。

1 个答案:

答案 0 :(得分:2)

您需要{{ policyForm }}而不是{{ policyform }}