FORMS PY from django import forms from django utils translation import

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
##################################################################################### FORMS.PY
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from acc.models import UserProfile, Country, GENDER_CHOICES, DRUGS_CHOICES, EDUCATION_CHOICES
attrs_dict = { 'class': 'required' }
class UserProfileForm(forms.Form):
username = forms.CharField(max_length=30, widget=forms.TextInput(attrs=attrs_dict))
password = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False))
password_again = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False))
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)))
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30, required=False)
birthday = forms.DateField()
country = forms.ModelChoiceField(queryset=Country.objects.all())
city = forms.CharField(widget=forms.Select)
gender = forms.CharField(widget=forms.Select(choices=GENDER_CHOICES))
drugs = forms.CharField(widget=forms.Select(choices=DRUGS_CHOICES))
education = forms.CharField(widget=forms.Select(choices=EDUCATION_CHOICES), required=False)
occupation = forms.CharField(required=False)
how_did_you_hear_about_us = forms.CharField(required=False)
how_you_can_help = forms.CharField(required=False)
about_me = forms.CharField(widget=forms.Textarea, required=False)
def clean(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))
if 'password' in self.cleaned_data and 'password_again' in self.cleaned_data:
if self.cleaned_data['password'] != self.cleaned_data['password_again']:
raise forms.ValidationError(_(u'You must type the same password each time'))
return self.cleaned_data
def save(self):
return UserProfile.objects.create_inactive_user(userdata=self.data)
##################################################################################### MODELS.PY
# -*- coding: utf-8 -*-
import datetime
import random
import re
import sha
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.db import models
from django.conf import settings
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from django.forms import ModelForm
GENDER_CHOICES = (
('M', 'Мужской'),
('F', 'Женский'),
)
DRUGS_CHOICES = (
('N', 'Никогда не употреблял'),
('Y', 'Употребляю сейчас'),
('A', 'Употреблял раньше'),
)
EDUCATION_CHOICES = (
('0', 'Среднее'),
('1', 'Среднее специальное'),
('2', 'Высшее'),
)
ISTOP_CHOICES = (
('0', 'Нет'),
('1', 'Да'),
)
class Country(models.Model):
country = models.CharField(max_length=100)
is_top = models.CharField(max_length=1, choices=ISTOP_CHOICES, default='0')
def __unicode__(self):
return self.country
class City(models.Model):
country = models.ForeignKey(Country)
city = models.CharField(max_length=100)
is_top = models.CharField(max_length=1, choices=ISTOP_CHOICES, default='0')
def __unicode__(self):
return self.city
class UserProfileManager(models.Manager):
def activate_user(self, activation_key):
if SHA1_RE.search(activation_key):
try:
profile = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not profile.activation_key_expired():
user = profile.user
user.is_active = True
user.save()
profile.activation_key = "ALREADY_ACTIVATED"
profile.save()
return user
return False
def create_inactive_user(self, *argv, **kwargs):
obj = kwargs['userdata'].copy()
new_user = User.objects.create_user(obj['username'], obj['email'], obj['password'])
new_user.is_active = False
new_user.save()
salt = sha.new(str(random.random())).hexdigest()[:5]
activation_key = sha.new(salt + obj['username']).hexdigest()
obj.appendlist('user', new_user.pk)
obj.appendlist('activation_key', activation_key)
p = PrivetaUserProfileForms(obj)
p.save()
if settings.ACCOUNT_SEND_EMAIL:
current_site = Site.objects.get_current()
subject = render_to_string('registration/activation_email_subject.txt',{ 'site': current_site })
subject = ''.join(subject.splitlines())
message = render_to_string('registration/activation_email.txt',
{ 'activation_key': registration_profile.activation_key,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
'site': current_site })
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [new_user.email])
return new_user
def delete_expired_users(self):
for profile in self.all():
if profile.activation_key_expired():
user = profile.user
if not user.is_active:
user.delete()
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
drugs = models.CharField(max_length=1, choices=DRUGS_CHOICES)
birthday = models.DateField(default=datetime.date.today())
country = models.ForeignKey(Country)
city = models.ForeignKey(City)
education = models.CharField(max_length=1, choices=EDUCATION_CHOICES, blank=True)
occupation = models.TextField(blank=True)
how_did_you_hear_about_us = models.TextField(blank=True)
how_you_can_help = models.TextField(blank=True)
about_me = models.TextField(blank=True)
activation_key = models.CharField(max_length=40)
objects = UserProfileManager()
def __unicode__(self):
return u"Registration information for %s" % self.user
# def activation_key_expired(self):
# expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
# return self.activation_key == "ALREADY_ACTIVATED" or (self.user.date_joined + expiration_date <= datetime.datetime.now())
#
#activation_key_expired.boolean = True
class PrivetaUserProfileForms(ModelForm):
class Meta:
model = UserProfile
##################################################################################### ADMIN.PY
from django.contrib import admin
from acc.models import UserProfile, Country, City
class RegistrationAdmin(admin.ModelAdmin):
pass
# list_display = ('__unicode__', 'activation_key_expired')
# search_fields = ('user__username', 'user__first_name')
class CountryAdmin(admin.ModelAdmin):
pass
class CityAdmin(admin.ModelAdmin):
pass
admin.site.register(UserProfile, RegistrationAdmin)
admin.site.register(Country, CountryAdmin)
admin.site.register(City, CityAdmin)