I am working on a recipe website based on django and have run into a snag on the custom backends.
I am receiving a Validation error -no exception supplied when I try to save my cookbook instance in the backend.
here is my backend:
from registration.backends.default import DefaultBackend
from cookbook.models import Cookbook
from django.contrib.auth.models import User
from registration.models import RegistrationProfile
class RecipeekActivationBackend(DefaultBackend):
def register(self, request, **kwargs):
new_user = super(RecipeekActivationBackend, self).register(request, **kwargs)
new_user.save()
cookbook = Cookbook(name=new_user.first_name, pub_date="12/12/2012", user=new_user)
print"cookbook"
cookbook.save()
return new_user
the error occurs at cookbook.save()
here is my Cookbook model:
class Cookbook(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
user = models.ForeignKey(User, related_name='cookbooks')
recipes = models.ManyToManyField('Recipe', related_name = 'cookbooks')
I believe that is all i need to supply in order to get a little help.
thank you in advance,
A. Cooper
update: the error was caused by pub_date being passed a string instead of a datetime update2: the way I am going about this is not the best way and i am now going to attempt to use signals to achieve the same outcome
You're going about this all wrong. Authentication backends are for one thing: authentication. The only reason you should be customizing a backend is if you're trying to tie authentication in from another system or need to make some other change like using email for username. Otherwise, use the defaults
Django provides signals for this exact purpose, so that's what you should use.
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_cookbook_for_user(sender, instance, created, *args, **kwargs):
if created and not instance.cookbooks.exists():
Cookbook.objects.create(name=instance.first_name, pub_date=date.today(), user=instance)
Put that in your models.py, and you're done.