0

我正在學習Django框架,但讓我開始使用一些django功能,而不是再次執行eveything。我開始使用模型表單,並且還看到了這個raise ValidationError功能,如果有任何錯誤,它將顯示。 我開始了與創建一個簡單的用戶登錄和註冊形式,它看起來像這樣:Django ModelForm ValidationError在網頁上不顯示

Models.py

from __future__ import unicode_literals 
from django.db import models 
from django.core.exceptions import ValidationError 
import re, bcrypt 


def check_uname(value): 
    if not re.match('^[.a-zA-Z0-9_]+$', value): 
     raise ValidationError('Invalid Username') 

def check_passwd(value): 
    if len(value) < 8 and not re.search(r'[A-Z]', value) and not re.search(r'[a-z]', value) and not re.search(r'[0-9]', value): 
     raise ValidationError('Invalid Password') 

def login(uname, passwd): 
    there = User.objects.filter(user_name=uname).values() 
    if there: 
     if bcrypt.hashpw((passwd).encode(), there[0]['password'].encode()) != there[0]['password'].encode(): 
      return "wrong" 
     else: 
      return there 

    else: 
     return "wrong" 

class User(models.Model): 
     full_name = models.CharField(max_length=45) 
     user_name = models.CharField(max_length=45, validators=[check_uname]) 
     email = models.EmailField(max_length=100) 
     password = models.CharField(max_length=100, validators=[check_passwd]) 
     created_at = models.DateTimeField(auto_now_add = True) 
     updated_at = models.DateTimeField(auto_now = True) 

Forms.py

from django import forms 
from .models import User 
from django.core.exceptions import ValidationError 
import bcrypt 
from django.db.models import Q 

class loginForm(forms.ModelForm): 

    class Meta: 
     model = User 
     fields = ['user_name', 'password'] 
     exclude = ['full_name', 'email'] 
     widgets = { 
     'password': forms.PasswordInput(), 
    } 



class regForm(forms.ModelForm): 
    password2 = forms.CharField(max_length=100, label="Comfirm password", required=True, widget=forms.PasswordInput()) 
    class Meta: 
     model = User 
     fields = ['full_name', 'user_name', 'email', 'password'] 
     widgets = { 
     'password': forms.PasswordInput(), 
     } 

    def clean(self): 
     if self.cleaned_data['password'] != self.cleaned_data['password2']: 
      print "Passwords do not match" 
      raise forms.ValidationError("Passwords do not match") 
     else: 
      user = User.objects.filter(Q(user_name=self.cleaned_data['user_name']) | Q(email=self.cleaned_data['email'])) 
      if user: 
       print "Username or Email already in use" 
       raise forms.ValidationError("Username or Email already in use") 
      else: 
       print ("hashing password") 
       unhashed_passwd = self.cleaned_data['password'].encode() 
       self.cleaned_data['password'] = bcrypt.hashpw(unhashed_passwd, bcrypt.gensalt()) 
     return (regForm, self).clean(*args, **kwargs) 

意見。 py

from django.shortcuts import render, redirect 
from django.contrib import messages 
from . import forms 
from . import models 
import bcrypt 

def login(request): 
    if 'user_id' not in request.session: 
     context = {'loginForm':forms.loginForm, 'regForm':forms.regForm} 

     if request.method == "POST" and 'password2' in request.POST: 
      reg_Form = forms.regForm(request.POST or None) 
      if reg_Form.is_valid(): 
       print "It is inside valid" 
       print errors 
       reg_Form.save() 

     else: 
      form = forms.loginForm(request.POST or None) 

      if form.is_valid(): 
       user_info = models.login(form.cleaned_data['user_name'], form.cleaned_data['password']) 
       if user_info == "wrong": 
        messages.error(request, 'Username or Password is invalid.') 
       else: 
        request.session['user_id'] = user_info[0]['id'] 

     return render(request, 'index.html', context) 

    else: 
     return redirect('/') 

模板

<!DOCTYPE HTML> 
<html> 

    <head> 
     <title></title> 
     <meta charset="utf-8"> 
     {% load staticfiles %} 
     <link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}"> 
     {% load bootstrap3 %} 
     {% bootstrap_css %} 
     {% bootstrap_javascript %} 
    </head> 

    <body> 

      <nav class="navbar navbar-inverse navbar-top"> 
       <div class="container"> 
        <a class="navbar-brand" href="#">Ketan.io</a> 
       </div> 
      </nav> 

     {% bootstrap_messages %} 

     <div class="container"> 
      <div class="row col-md-6"> 
       <ol class="breadcrumb"> 
        <h3><li>Login</li></h3> 
       </ol> 
       <form action="/login/" method="post" class="form-inline"> 
        {% csrf_token %} 
        {% bootstrap_form_errors loginForm %} 
        {% bootstrap_form loginForm show_label=False %} 
        {% bootstrap_button "Login" button_type="submit" button_class="btn-primary" %} 
       </form> 
      </div> 

      <div class="margin_left col-md-6"> 
       <ol class="breadcrumb"> 
        <h3><li>Register</li></h3> 
       </ol> 
       <form action="/login/" method="post" class="form"> 
        {% csrf_token %} 
        {% bootstrap_form_errors regForm %} 
        {% bootstrap_form regForm show_label=False %} 
        {% bootstrap_button "Register" button_type="submit" button_class="btn-primary" %} 
       </form> 
      </div> 

     </div> 

    </body> 
</html> 

請讓我知道如果我做錯什麼!我想讓ValidationError在HTML上彈出。我確定驗證正在工作,因爲我也在打印語句的幫助下檢查它們。 我對此很陌生,至今仍在學習。我可能不會使用最佳實踐,但在實踐中一定會更好。

問候和歡呼。

回答

0

的錯誤是在您的上下文

你是不是送你的表格

context = {'loginForm':forms.loginForm, 'regForm':forms.regForm} 

兩個loginFormregForm適當的實例表單類,而不是實例。因此,在初始化後將表格附加到上下文字典中

def login(request): 
    if 'user_id' not in request.session: 
     context = {} 

     if request.method == "POST" and 'password2' in request.POST: 
      reg_Form = forms.regForm(request.POST or None) 
      context.update({'regForm':reg_Form}) 


      if reg_Form.is_valid(): 
       print "It is inside valid" 
       print errors 
       reg_Form.save() 

     else: 
      form = forms.loginForm(request.POST or None) 
      context.update({'loginForm':form}) 
      if form.is_valid(): 
       user_info = models.login(form.cleaned_data['user_name'], form.cleaned_data['password']) 
       if user_info == "wrong": 
        messages.error(request, 'Username or Password is invalid.') 
       else: 
        request.session['user_id'] = user_info[0]['id'] 

     return render(request, 'index.html', context) 

    else: 
     return redirect('/')