我正在学习Django框架,但我让我开始使用一些django功能,而不是再次执行eveything。我开始使用模型表单,并且还看到了这个raise 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)
Views.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>
如果我做错了什么,请告诉我!我想在HTML上弹出ValidationError
。我确信验证工作正常,因为我也在打印语句的帮助下检查它们。
我对此非常陌生并且还在学习。我可能还没有使用最佳实践,但通过练习肯定会更好。
问候和欢呼。
答案 0 :(得分:0)
错误在您的上下文中
您没有发送表格的正确实例
context = {'loginForm':forms.loginForm, 'regForm':forms.regForm}
loginForm
和regForm
都是您的表单类,而不是实例。因此,在初始化之后将表单附加到上下文dict
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('/')