0

私はDjangoフレームワークを学んでいますが、私はeveythingをやり直すのではなく、いくつかのdjango機能を使い始めます。私はモデルフォームを使い始めましたが、何かエラーがあれば表示されるこのraise ValidationErrorの機能も見ました。 私はシンプルなユーザーログインと登録フォームの作成をオフに開始し、それは次のようになります。Webページに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('/') 
関連する問題