0

Ich lerne das Django Framework, aber ich lasse mich mit einigen der Django Features beginnen, anstatt alles wieder zu tun. Ich fing an, Modellformen zu verwenden und sah auch diese raise ValidationError Eigenschaft, die angezeigt wird, wenn es irgendwelche Fehler gibt. Ich begann mit der Erstellung einer einfachen Benutzeranmeldung und Anmeldeformular aus und sieht wie folgt aus:Django ModelForm ValidationError wird nicht auf der Webseite angezeigt

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) 

Ansichten. 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('/') 

Vorlage

<!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> 

Bitte lassen Sie mich wissen, wenn ich etwas falsch tue! Ich möchte, dass die ValidationError auf dem HTML erscheint. Ich bin mir sicher, Validierungen funktionieren, weil ich sie auch mit Hilfe von print-Anweisungen überprüfe. Ich bin sehr neu und lerne immer noch. Ich werde vielleicht noch nicht die Best Practices anwenden, werde aber mit der Übung definitiv besser werden.

Grüße und Prost.

Antwort

0

Der Fehler ist in Ihrem Kontext

Sie sind nicht die richtigen Instanzen Ihrer Formulare

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

Beide loginForm und regForm senden die Formularklassen sind, keine Instanzen. Also, fügen Sie die Formulare an den Kontext dict nach der Initialisierung sie

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('/')