Django表单不呈现。 <位于0x000002C7B3B37A20的<TestForm.forms.my_form对象>

时间:2019-12-21 17:35:03

标签: python django django-forms

我正在尝试在模板中呈现表单。 这是我的模特:

from django.db import models
from phonenumber_field.modelfields import PhoneNumberField


class StudyRequest(models.Model):
    name = models.CharField(max_length=256, blank=True)
    phone = PhoneNumberField(unique=True, blank=False, null=False)

我的表单:

from .models import *
from django import forms
from phonenumber_field.formfields import PhoneNumberField


class send_request_form():
    phone = PhoneNumberField(required=True)
    name = forms.CharField(max_length=256, required=False)

    class Meta:
        model = StudyRequest
        fields = {'name', 'phone'}

我的观点:

from django.shortcuts import render, redirect
from StudyRequest.forms import send_request_form
from StudyRequest.models import StudyRequest


def landing_page(request):
    if request.method == 'POST':
        form = send_request_form(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            phone = form.cleaned_data['phone']
            R = StudyRequest(name=name, phone=phone)
            R.save()
    else:
        form = send_request_form()
    return render(request, 'NetStudy/home.html', {'form': form})

这是渲染的结果: enter image description here

HTML:

<html>
<head></head>
<body>
<form>
    {% csrf_token %}
    {{ form }}
</form>
</body>
</html>

我尝试使用form.as_p,form.as_table,form.as_ul,没有任何帮助。

1 个答案:

答案 0 :(得分:0)

问题出在表单中。py表单应该继承Django表单。

from .models import *
from django import forms
from phonenumber_field.formfields import PhoneNumberField


class send_request_form(forms.ModelForm):
    phone = PhoneNumberField(required=True)
    name = forms.CharField(max_length=256, required=False)

    class Meta:
        model = StudyRequest
        fields = {'name', 'phone'}