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.
234 lines
9.6 KiB
234 lines
9.6 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, Profile
|
|
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, is_latin
|
|
|
|
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.CharField(label='Город', widget=forms.HiddenInput())
|
|
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())
|
|
|
|
|
|
class RegistrationCompleteForm(forms.ModelForm):
|
|
country = forms.ChoiceField(label='Страна', choices=[(c.id, c.name) for c in Country.objects.all()],
|
|
widget=forms.Select(attrs={'class': 'select2'}))
|
|
city = forms.CharField(label='Город', widget=forms.HiddenInput())
|
|
url = forms.CharField(widget=forms.TextInput(attrs={'placeholder': _(u'адрес страны(обязательно)')}))
|
|
|
|
code_country = forms.ChoiceField(label=_(u'код страны'), initial='70',
|
|
choices=[(str(c.phone_code), '+'+str(c.phone_code)) for c in Country.objects.all() if c.phone_code is not None],
|
|
widget=forms.Select(attrs={'class': 'select2'}))
|
|
code_city = forms.CharField(label=_(u'код города'))
|
|
phone = forms.CharField(label=_(u'ваш номер'))
|
|
class Meta:
|
|
model = User
|
|
fields = ('url',)
|
|
|
|
|
|
def save(self, force_insert=False, force_update=False, commit=True):
|
|
user = super(RegistrationCompleteForm, self).save(commit=False)
|
|
data = self.cleaned_data
|
|
phone = data['code_country']+data['code_city']+data['phone']
|
|
|
|
user.profile.phone = int(phone)
|
|
user.profile.country = data['country']
|
|
user.profile.city = data['city']
|
|
user.profile.save()
|
|
|
|
if commit:
|
|
user.save()
|
|
return user
|
|
|
|
def clean_city(self):
|
|
try:
|
|
return City.objects.get(id=self.cleaned_data['city'])
|
|
except City.DoesNotExist:
|
|
return None
|
|
|
|
|
|
def clean_country(self):
|
|
try:
|
|
return Country.objects.get(id=self.cleaned_data['country'])
|
|
except City.DoesNotExist:
|
|
return None
|
|
|
|
def clean_url(self):
|
|
url = self.cleaned_data['url']
|
|
if not is_latin(url):
|
|
raise forms.ValidationError(_(u'url должен состоять только из латинских букв'))
|
|
|
|
try:
|
|
User.objects.get(url=url)
|
|
raise forms.ValidationError(_(u'Пользователь с таким url уже существует'))
|
|
except User.DoesNotExist:
|
|
return url
|
|
|
|
|
|
|
|
|
|
class RecoveryForm(forms.Form):
|
|
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': _(u'Email')}))
|
|
|
|
def get_user(self):
|
|
email = self.cleaned_data['email']
|
|
return User.objects.get(email=email)
|
|
|
|
def clean_email(self):
|
|
email = self.cleaned_data['email']
|
|
try:
|
|
return User.objects.get(email=email)
|
|
except User.DoesNotExist:
|
|
raise forms.ValidationError(_(u'Пользователь с таким емейлом не зарегестрирован'))
|
|
|
|
|
|
|
|
|