##################################################################################### 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)