Django表单验证未显示在模板

时间:2018-03-13 11:09:14

标签: django forms validation templates

我的问题是,当我验证表单的错误时,会显示一些带警告的文本​​,但是id不会。我正在寻找2天的一些好的答案,我也尝试了一切,所以我觉得这是一个非常愚蠢的错误。任何人都可以帮我解决这个问题吗?

我试图在我的注册子页面中实现验证,所以......

首先是我的model.py进行注册

from django.db import models


class User(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField(max_length=30)
    password = models.CharField(max_length=30)

    def __str__(self):
        return "Login: " + self.name + \
               " | e-mail: " + self.email + \
               " | password: " + self.password

其次是我的inputForms.py,带有简单验证

from django import forms
from django.contrib.auth.models import User
from django.contrib import messages
from .models import User


class NewUser(forms.Form):
    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    password = forms.CharField(widget=forms.PasswordInput, required=True)
    pic1 = forms.CharField(required=True)
    pic2 = forms.CharField(required=True)
    pic3 = forms.CharField(required=True)
    pic4 = forms.CharField(required=True)
    pic5 = forms.CharField(required=True)

    class Meta:
        model = User
        fields = ('name', 'email', 'password')

    def clean_email(self):
        email_passed = self.cleaned_data.get('email')
        email_req = "yourdomain.com"
        if not email_req in email_passed:
            raise forms.ValidationError("Not a valid email. Please try again")
        return email_passed

第三是我的view.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from definitions import SITE_ROOT
from .models import User
from . import inputForms
from threading import Thread
import base64
import re
import os


def index(request):
    if request.method == 'GET':
        return render(request, 'register.html', {'NewUser': inputForms.NewUser})
    else:
        return HttpResponseRedirect('/Kniznica')


def new_user(request):
    if request.method == 'POST':
        form = inputForms.NewUser(request.POST)
        if form.is_valid():
            user_name = form.cleaned_data['name']
            user_email = form.cleaned_data['email']
            user_password = form.cleaned_data['password']
            thread = Thread(target=save_user, args=(form, user_name, user_email, user_password, ))
            thread.start()
            return HttpResponseRedirect('/Kniznica')
        else:
            return render(request, "register.html", {'NewUser': inputForms.NewUser})


def save_user(form, user_name, user_email, user_password):
    base_to_png(form.cleaned_data['pic1'], user_name, "face1.png")
    base_to_png(form.cleaned_data['pic2'], user_name, "face2.png")
    base_to_png(form.cleaned_data['pic3'], user_name, "face3.png")
    base_to_png(form.cleaned_data['pic4'], user_name, "face4.png")
    base_to_png(form.cleaned_data['pic5'], user_name, "face5.png")
    user_instance = User.objects.create(name=user_name, email=user_email, password=user_password)
    user_instance.save()


def base_to_png(base64_string, name, image_name):
    string_without_header = re.sub('^data:image/.+;base64,', '', base64_string)
    img_data = base64.b64decode(string_without_header)
    if not os.path.exists(SITE_ROOT + "/faceId/" + name):
        os.makedirs(SITE_ROOT + "/faceId/" + name)
    filename = SITE_ROOT + "/faceId/" + name + "/" + image_name
    with open(filename, 'wb') as f:
        f.write(img_data)
    os.chdir(SITE_ROOT + "\static\scripts")
    os.system("node face-detection.js " + name + " " + image_name)

第四个是我的template.html进行注册

<div>
    <form action="newUser" method="post" novalidate>
        {% csrf_token %}
        {{ form.non_field_errors }}
        {{ form.username.errors }}
        {% if form.errors %}
            {% for field in form %}
                {% for error in field.errors %}
                    <p> {{ errors }} </p>
                {% endfor %}
            {% endfor %}
        {% endif %}
        <div style="display: inline-block">
            Meno:{{ NewUser.name }}
        </div>
        <div style="display: inline-block">
            Email:{{ NewUser.email }}
        </div>
        <div style="display: inline-block">
            Heslo:{{ NewUser.password }}
        </div>
        <div hidden>
            {{ NewUser.pic1 }}
            {{ NewUser.pic2 }}
            {{ NewUser.pic3 }}
            {{ NewUser.pic4 }}
            {{ NewUser.pic5 }}
        </div>
        <div>
            <video id="video" width="300" height="300" autoplay></video>
        </div>
        <div>
            <p id="counter"></p>
            <button type="button" id="snap">Snap Photo</button>
            <button type="submit" id="save" name="register">Registrácia</button>
        </div>
        <canvas hidden id="canvas" width="640" height="480"></canvas>
    </form>
</div>

有人请帮我解决这个错误。非常感谢你。

1 个答案:

答案 0 :(得分:0)

这里有一个不寻常的视图结构 - 通常你会使用相同的视图来显示初始表单,就像处理提交和显示错误一样。

但是,你确实有一些明显的问题。首先,在您的new_user视图中,当表单无效时,您不会发回该无效表单,而是发送表单类本身。你应该总是发送一个表格的实例,在这种情况下你应该发回你已经验证的同一个实例,因为那是错误的事情:

return render(request, "register.html", {'NewUser': form})

其次,在您的模板中,您对所谓的表单不一致。渲染字段时,可以通过NewUser访问它。但是在尝试显示错误时,出于某种原因,您将其称为form。当您从视图中发送名称时使用名称NewUser,您应该使用它来显示错误:

{{ NewUser.errors }}