There seem to be quite a few issues related to circular import errors just with models, but I seem to be getting a similar problem with my model and signal callbacks. I’m fairly new to Django, so in all likelihood it’s more to do with me not structuring my app correctly. Some code:
badges/models.py:
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from tasks import badgeaward_callback
class Award(models.Model):
user = models.ForeignKey(User)
description = models.TextField(blank=False)
award_date = models.DateTimeField('date awarded',default=datetime.now)
def __unicode__(self):
return self.description
class Points(models.Model):
POINT_TYPES = (
('signup', 'Sign up'),
...etc...
)
user = models.ForeignKey(User)
points = models.IntegerField()
date = models.DateTimeField('date created',default=datetime.now)
description = models.TextField(blank=False)
data = models.TextField(blank=True)
type = models.CharField(max_length=20,choices=POINT_TYPES)
def __unicode__(self):
return self.description
models.signals.post_save.connect(badgeaward_callback, sender=Award)
badges/tasks.py
from badges.models import Points
def badgeaward_callback(sender, **kwargs):
award = kwargs.get('award')
p = Points()
p.points = 100
p.type = 'badgeawarded'
p.description = award.description
p.user = award.user
p.save()
So, models is importing badgeaward_callback (this is the error I get: cannot import name badgeaward_callback), but tasks is importing Points model – I assume this is the root cause of my error.
Any advice on how I should be structuring my app is much appreciated. Should I just put my badgesaward_callback into models.py? That works (well, no more error), but is it a good approach when later I may be adding quite a few more callback functions?
In terms of better structure, instead of
tasks.pyrename itsignals.pyand from models.pymove this line to
signals.pyat end. Then you don’t require the importfrom tasks import badgeaward_callbackin models.py