Tuesday, January 31, 2012

Customising django registration - no activation email or just a username

A client had a need for removing the email activation from the standard django registration process and a prototype system I am working on needed the ability to create a user from just a username, so I was delighted to find that the current django-registration development version makes this kind of customisation easy.

Here's how:

In the registration folder, there is a new folder called backends. Create a new folder, for example myreg, and put two files in it.

The __init__.py does the main work:

In this example there are two changes from the default, there is no email activation required and the registration form also asks for the users first and last names.

__init__.py


from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from django import forms

from registration import signals
from registration.forms import RegistrationForm


class MyRegBackend(object):
"""
A registration backend which implements the simplest possible
workflow: a user supplies a username, email address and password
(the bare minimum for a useful account), and is immediately signed
up and logged in.

"""
def register(self, request, **kwargs):
"""
Create and immediately log in a new user.

"""
username, email, password, first_name, last_name = kwargs['username'], kwargs['email'], kwargs['password1'], kwargs['first_name'], kwargs['last_name']

u = User.objects.create_user(username, email, password)
u.first_name = first_name
u.last_name = last_name
u.save()

new_user = authenticate(username=username, password=password)

login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user

def activate(self, **kwargs):
raise NotImplementedError

def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:

* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.

* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.

"""
return getattr(settings, 'REGISTRATION_OPEN', True)

def get_form_class(self, request):

class MyRegForm(RegistrationForm):

"""
add first and last names to the form
"""
first_name = forms.CharField(
label='First name',
max_length=30,
required=True)
last_name = forms.CharField(
label='Last name',
max_length=30,
required=True)


return MyRegForm

def post_registration_redirect(self, request, user):
"""
After registration, redirect to the home page

"""

return ("/", (), {})

def post_activation_redirect(self, request, user):
raise NotImplementedError


The second file is urls.py where you need to point to your new backend

urls.py


from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from registration.views import activate
from registration.views import register


urlpatterns = patterns('',
url(r'^register/$',
register,
{'backend': 'registration.backends.myreg.MyRegBackend'},
name='registration_register'),
url(r'^register/closed/$',
direct_to_template,
{'template': 'registration/registration_closed.html'},
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)



Now an even simpler version. Just enter a username and the user is created and you are logged in. Note that I wanted a default password so I made password1 a hidden field on the form with the value I wanted so that is how it is able to create the user. I could also have hard coded it into the register method below.


__init__.py


from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User

from registration import signals
from registration.forms import RegistrationForm


class MyReg2Backend(object):
"""
A registration backend which implements the simplest possible
workflow: a user supplies a username, email address and password
(the bare minimum for a useful account), and is immediately signed
up and logged in.

"""
def register(self, request, **kwargs):
"""
Create and immediately log in a new user.

"""
username, email, password = kwargs['username'], kwargs['email'], kwargs['password1']
User.objects.create_user(username, email, password)

# authenticate() always has to be called before login(), and
# will return the user we just created.
new_user = authenticate(username=username, password=password)
login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user

def activate(self, **kwargs):
raise NotImplementedError

def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:

* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.

* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.

"""
return getattr(settings, 'REGISTRATION_OPEN', True)

def get_form_class(self, request):
return RegistrationForm

def post_registration_redirect(self, request, user):
"""
After registration, redirect to the user's account page.

"""
return (user.get_absolute_url(), (), {})

def post_activation_redirect(self, request, user):
raise NotImplementedError



Now in urls.py you just need to call your new backend

urls.py


from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from registration.views import activate
from registration.views import register


urlpatterns = patterns('',
url(r'^register/$',
register,
{'backend': 'registration.backends.myreg2.MyReg2Backend', 'template_name': 'registration/registration_form_quick.html'},
name='registration_register'),
url(r'^register/closed/$',
direct_to_template,
{'template': 'registration/registration_closed.html'},
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)

Sunday, December 4, 2011

Is cat food addictive (for cats!)


A friend brought some fancy Felix cat food in sachets when I asked her to pick up a bit of cat food on her way here. My cats are outside cats. Their normal diet is dried cat food once a day with small beasties as they catch them. Just occasionally they get a tin of cat food for a treat. They do well on this diet always looking sleek and shiney.

Anyway they wolfed down the Felix that night and I thought no more about it. Next morning I was mobbed at the door as though they hadn't been fed for days. They spent the whole day at this and finally got their fix in the evening. Next day the same. Thankfully the Felix sachets are finished and their behaviour is returning to normal. What was that about?

Friday, April 15, 2011

Green shoots and old scaffolding boards


Long, long ago I was a great fan of Geoff Hamilton's Gardener's World on the BBC. Geoff was a great man for showing us how to knock up useful garden items from a few old boards and some nails. With the untimely loss of Geoff we moved on to a new generation of presenters who reviewed the range of products we could purchase from our local garden centre and I rather lost interest in the program. Two bits of great news. Monty Don is back presenting Gardener's World, a real gardener and not a bit of garden centre tat in sight. Then, fired with a renewed enthusiasm for gardening programs, I tried RTE's How to Create a Garden and there were the good old scaffolding boards and how to make your own cold frame. Isn't it great to seem some attention given to build your own instead of buy your own!

Monday, February 21, 2011

How I'm going to vote in General Election 2011

I've been struggling with how to vote as I don't feel any of the main parties are looking much beyond the end of their noses in their plans to fix things - or return to a sustainable economy as Fianne Fail puts it!

I want to see fundamental change in how we view the economy, in our use of non-renewable resources and a more imaginative and long term approach to planning for the future. I want to see more power at the local level along with people getting more involved in our own government. I want to a split in the political system between politicians how look after local and individual issues and those that are minding the country. I could go on....

No fundamental change is going to come with the current, well established people and systems of government so I will vote for whichever party will make the most fundamental changes in the way we govern ourselves that give a chance for change to happen AND for the party which makes the most effort to involve women.

I don't believe women make better decisions than men, or that men make better decisions than women, but I do believe that men and women together make better decisions. But for this to happen women must be allowed to be women and not feel we have to play the men's games better than them. Apparently men tend to make decisions that take advantage of the current situation whereas women are more likely to look at the long terms consequences of a decision and judge according. This make perfect sense to me and shows how men and women working together make better balanced decisions. This TED talk makes a similar point:


Now to the research. Any comments on who you think is doing best in this area very welcome!

Monday, December 13, 2010

Including Jpeg support in PIL on centos box

There are a lot of posts out that say to install the libraries jpeg and jpeg-devel prior to installing PIL, but this did not work for me on Cento. For example this site http://www.jroller.com/RickHigh/entry/installing_pil_python_image_library suggests using the command:

$ sudo yum install freetype freetype-devel jpeg jpeg-devel libpng libpng-devel
Setting up Install Process
Setting up repositories
Reading repository metadata in from local files
Parsing package install arguments
No Match for argument: jpeg <<----- note the error here
No Match for argument: jpeg-devel <<----- and here
Resolving Dependencies
--> Populating transaction set with selected packages. Please wait.
---> Downloading header for libpng to pack into transaction set.
......



Instead use:

$ sudo yum install freetype freetype-devel libpng libpng-devel libjpeg libjpeg-devel


If you have already got as far as installing PIL, delete it from the site-packages directory and reinstall, I use easy_install PIL, and this will rebuild PIL, this time with jpeg support.

--------------------------------------------------------------------
*** TKINTER support not available
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE2 support available
*** LITTLECMS support not available
--------------------------------------------------------------------

Sunday, October 3, 2010

Training Horses like learning a Language?


I've been trying to articulate how my methods of training horses have changed over the last couple of years, thanks to a number of books and in particular Clinton Anderson. It's about teach that when a give a certain aid, this is what I want the horse to do. But isn't that what I've always done? Take for example teach a rein back. I would apply some pressure on the reins and a bit of leg and keep increasing the pressure until the horse would step back, then I would reward him. Over time I would hope to reduce the amount of pressure I'd require to get the rein back.

The new method is only subtly different. First I will teach the reinback from the ground, light pressure on the chest means go back, then when I'm on board apply gentle pressure with the reins at the same time a pulling a rope around the horses neck. The instant the horse makes any attempt to go back, I drop the reins to indicate that was the right thing to do. After a bit I'll stop using the rope and include moving my weight back and finally add use of the legs. This way I've broken down the problem into steps and never had to apply a lot of pressure to show what I want. This second approach has meant my horses have become much lighter and stop and reinback with much less resistance because they have learnt the language of the aids.

So I would say my old method was like arriving in a new country where nobody speaks my language and beyond speaking a bit slower and louder, I don't get any help in learning this language. It is a slow and painful process! The second method is like having a teacher coming with you a helping gain fluency step by step at a pace that suits you. So as a horse trainer, I am focusing more on my skills as a teacher than my skills as a rider.

Tuesday, May 4, 2010

Mad Dog the Superstar


Travelled up to Kilkenny yesterday (3.5 hours each way) for the excellent Amateur show that is held there on May Bank Holiday each year. It's been lucky for me in the past, but with no show since last October and straight into one of the toughest competitions of the year, I was stomach churningly nervous as I wait for the class to get under way. I needn't have worried, Mad Dog shook off the winter blues and returned to form to win the class in fine style, loving all the excitement and attention. Supercub finished fourth in the later speed class so very tired but happy horses and rider arrived home late last night.

http://stabletostable.com/en/2010/05/kilkenny-sji-amateurs-warrington-ec-03052010/