首页 > 解决方案 > 我不明白为什么我的表单没有在 django 中验证

问题描述

我还是 django 的新手。玩了一个leadmanager应用程序,我不知道为什么我的表单没有验证。

意见

def index(request):
    lead=LeadForm()
    if request.method == 'POST':
        lead=LeadForm(request.POST)
        if lead.is_valid():
            messages.success(request, f'Thank you for registering. Someone will be contacting you soon.')
            return redirect('index')
        else:
            lead=LeadForm()
            messages.error(request, f'Something went wrong. Please try again later.')
        
    return render(request, "frontend/index.html", {'lead':lead})

在 index.html 中

<form action="" method="POST" class="lead-form">
    {% csrf_token %}
    <fieldset class="lead-info">
        <div class="form-control">
            <label for="">Full Name</label>
            {{ lead.fullname }}
        </div>
        <div class="form-control">
            <label for="">Email</label>
            {{ lead.email }}
        </div>
        <div class="form-control">
            <label for="">Phone</label>
            {{ lead.phone }}
        </div>
        <div class="form-control">
            <label for="">City</label>
            {{ lead.city }}
        </div>
    </fieldset>
             <button type="submit" class="btn-pill">Submit</button>
</form>

在forms.py中

class LeadForm(forms.ModelForm):
    email = forms.EmailField()
    class Meta:
        model = Lead 
        fields = ['fullname', 'email', 'phone', 'city', 'contact_preference']
        widgets = {'contact_preference': forms.RadioSelect }

任何帮助表示赞赏。contact_preference 正在渲染仅供参考,我只是剪掉了代码以使这个问题不那么长。

标签: djangodjango-formsdjango-viewsdjango-templates

解决方案


推荐阅读