You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

159 lines
6.9 KiB

# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.forms.util import ErrorList
from django.utils.translation import ugettext as _
from models import User
from country.models import Country
from city.models import City
from company.models import Company
from organiser.models import Organiser
#functions
from functions.form_check import translit_with_separator
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput(render_value=False))
password2 = forms.CharField(label='Повторите пароль', widget=forms.PasswordInput(render_value=False))
class Meta:
model = User
fields = ('email', 'first_name', 'last_name')
def clean_email(self):
"""
checking if user already exist
"""
email = self.cleaned_data.get('email')
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError('Пользователь с таким email уже существует')
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('Пароли не совпадают')
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password2'])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = User
def clean_password(self):
return self.initial['password']
class UserForm(forms.ModelForm):
email = forms.EmailField(widget=forms.TextInput(attrs={'disabled' : True}), required=False)
country = forms.ModelChoiceField(label='Страна', queryset=Country.objects.all(), empty_label=None, required=False)
city = forms.ModelChoiceField(label='Город', queryset=City.objects.all(), empty_label='', required=False)
company = forms.ModelChoiceField(label='Компания', queryset=Company.objects.all(), empty_label='', required=False)
organiser = forms.ModelChoiceField(label='Организатор', queryset=Organiser.objects.all(), empty_label='', required=False)
title = forms.CharField(widget=forms.TextInput(attrs={'style':'width: 550px'}), required=False)
descriptions = forms.CharField(widget=forms.TextInput(attrs={'style':'width: 550px'}), required=False)
keywords = forms.CharField(widget=forms.TextInput(attrs={'style':'width: 550px'}), required=False)
class Meta:
model = User
exclude = ('last_login', 'password', 'is_active', 'is_admin', 'is_superuser', 'is_staff'
'date_joined', 'date_registered', 'date_modified')
def clean_url(self):
url = self.cleaned_data.get('url')
try:
user = User.objects.get(url=translit_with_separator(url))
if (user.url == translit_with_separator(url)):
return url
except:
return url
raise forms.ValidationError('Такой урл уже занят')
def clean_phone(self):
"""
phone code checking
"""
cleaned_data = super(UserForm, self).clean()
phone = cleaned_data.get('phone')
if not phone:
return
deduct = ('-','(',')','.',' ')
for elem in deduct:
phone = phone.replace(elem, '')
if phone.isdigit():
return phone
else:
raise forms.ValidationError('Введите правильный код страны')
def clean_web_page(self):
cleaned_data = super(UserForm, self).clean()
web_page = cleaned_data.get('web_page')
if not web_page:
return web_page
import socket
try:
socket.getaddrinfo(web_page, 80)
return web_page
except:
return forms.ValidationError('Введите правильный адрес страници')
class ChangePasswordForm(forms.Form):
"""
Form to change password
"""
old_password = forms.CharField(label=_(u'Old password'), required=True,
widget=forms.PasswordInput(render_value=False,
attrs={'placeholder': _(u'Введите старый пароль')}))
new_password = forms.CharField(label=_(u'New password'), required=True,
widget=forms.PasswordInput(render_value=False,
attrs={'placeholder': _(u'Придумайте новый пароль')}))
new_password_confirm = forms.CharField(label=_(u'Confirm password'), required=True,
widget=forms.PasswordInput(render_value=False,
attrs={'placeholder': _(u'Повторите новый пароль')}))
def clean(self):
data = super(ChangePasswordForm, self).clean()
password1 = data.get('new_password')
password2 = data.get('new_password_confirm')
if not password1 or not password2:
return data
# self._errors['new_password'] = ErrorList([_(u'Different passwords!')])
# return data
if password1 and password2 and password1 != password2:
# check if passwords exists and equal
self._errors['new_password'] = ErrorList([_(u'Пароли не совпадают!')])
self._errors['new_password_confirm'] = ErrorList([_(u'Пароли не совпадают!')])
del data['new_password_confirm']
del data['new_password']
return data
if not password1.isdigit() and any(char.isdigit() for char in password1) and len(password1)>5:
# password must contain digits and letters and length > 5
return data
else:
self._errors['new_password'] = ErrorList([_(u'Пароль должен содержать цифры и буквы')])
self._errors['new_password_confirm'] = ErrorList([_(u'Пароль должен содержать цифры и буквы')])
del data['new_password']
del data['new_password_confirm']
return data
class EmailAnnouncementForm(forms.Form):
data = [(1, _(u'Получать приглашения, сообщения и другую корреспонденцию от пользователей Expomap')),
(2, _(u'Получать обзор событий')),
(3, _(u'Получать новости'))]
announcement = forms.MultipleChoiceField(choices=data, widget=forms.CheckboxSelectMultiple())