I'm currently trying to build a blog using Django. I've been facing this error for a few hours now. I'm not quite sure if this has anything to do with the directories but the error occurs when I try to register my model in the admin.py file.
from django.contrib import admin
from .models import Post
# Register models
admin.site.register(Post)
The directories look as follows:
blog
models
Post
Category
admin.py
settings
static
templates
Trace:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7ffb589a67b8>
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run
autoreload.raise_last_exception()
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute
autoreload.check_errors(django.setup)()
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate
app_config.ready()
File "/usr/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/hallak/Projects/hallak.io/hallak_blog/admin.py", line 5, in <module>
admin.site.register(Post)
File "/usr/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 102, in register
for model in model_or_iterable:
TypeError: 'module' object is not iterable
Post:
from django.db import models
from django.utils import timezone
class Post(models.Model):
# Auto-generated ID
id = models.AutoField(primary_key=True)
# Title
title = models.CharField(max_length=100)
# Slug
slug = models.SlugField(max_length=100)
# Content
body = models.TextField()
# Timestamps
created_on = models.DateField(auto_now_add=True)
published_on = models.DateTimeField(blank=True, null=True)
# Category
category = models.ForeignKey('.Category', on_delete=models.DO_NOTHING)
# Author
author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING)
# Publish post
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Category:
from django.db import models
class Category(models.Model):
# Auto-generated ID
id = models.AutoField(primary_key=True)
# Title
title = models.CharField(max_length=100)
# Slug
slug = models.SlugField(max_length=100)
# Timestamps
created_on = models.DateField(auto_now_add=True)
The error is happening here: https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L100-L101
Whenever I comment the register line everything works fine.
Instead of writing "from .models import Post" you should write "from .models.Post import Post".
First "Post" is a modulename (file name), second one is a class name.
Related
Admittedly I’m a newbie to django and I’m getting the following error when trying to run python manage.py makemigrations
I’m trying to add a new field in to my class Product(models.Model):
featured = models.BooleanField()
Code
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120) # max_length = required
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10000)
summary = models.TextField()
featured = models.BooleenField() #only new added line
Error: AttributeError: module 'django.db.models' has no attribute 'BooleenField'
command:
python manage.py makemigrations <enter>
entire_traceback:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\.....\trydjango\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\.....\trydjango\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\.....\trydjango\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\.....\trydjango\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\.....\trydjango\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\.....\src\products\models.py", line 4, in <module>
class Product(models.Model):
File "C:\.....\src\products\models.py", line 9, in Product
featured = models.BooleenField()
AttributeError: module 'django.db.models' has no attribute 'BooleenField'
There is an error in your code for the Product models.
I have corrected it.
from django.db import models
class Product(models.Model):
title = models.CharField(max_length=120) # max_length = required
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10000)
summary = models.TextField()
featured = models.BooleanField() #only new added line
the default value for a boolean field is always false.
I am creating a blog app from the book django 2 by example by antonio mele.
I am on the sub topic creating model managers.
However, as soon as i edit my models.py file, the power shell window that hosts the local server displays this error:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03B61300>
Traceback (most recent call last):
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
r_run
autoreload.raise_last_exception()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\public\django\my_env\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\public\django\mysite\blog\models.py", line 1, in <module>
class PublishedManager(models.Manager):
NameError: name 'models' is not defined
This is the code on the models.py file
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
# ...
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager
#TDK im not sure what youmean by 'includes' but this is the the admin.py file
from django.contrib import admin
from .models import Post
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'author', 'publish',
'status')
list_filter = ('status', 'created', 'publish', 'author')
search_fields = ('title', 'body')
prepopulated_fields = {'slug': ('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ('status', 'publish')
# Tony and Jonah, i added the code from django.db import models
and i get this error message too
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x030233D8>
Traceback (most recent call last):
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inne
r_run
self.check(display_num_errors=True)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\base.py", line 425, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'title', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'slug', which is not a callable, a
n attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'author', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'publish', which is not a callable
, an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'status', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
System check identified 5 issues (0 silenced).
Am really i was sharing the wrong models.py file.
# Daniel This complete code in the file:
from django.db import models
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
# ...
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager
and this is the error message i am getting now
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x036C1420>
Traceback (most recent call last):
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
r_run
autoreload.raise_last_exception()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\public\django\my_env\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\public\django\mysite\blog\models.py", line 9, in <module>
class Post(models.Model):
File "C:\Users\public\django\mysite\blog\models.py", line 17, in Post
author = models.ForeignKey(User,
NameError: name 'User' is not defined
As i alluded to in my comment, you’ve probably forgotten to include
from django.db import models
Now that error has gone it looks like you also need
from django.contrib.auth.models import User
I'm guessing you haven't imported the models code:
from django.db import models
I am trying to use the CsvModel module from django-adaptors. However, when i use from adaptor.model import CsvModel and makemigrations, below errors occured.
Can anyone advise the reason why? my code in the model is as follows:
from django.db import models
from adaptor.model import CsvModel
from adaptor.fields import CharField, DecimalField
class User(models.Model):
user_name = models.CharField(max_length = 50, null=True, unique=True)
def __str__(self):
return self.user_name
class Profile(models.Model):
rubbish = models.DecimalField(max_digits= 1000, decimal_places=3, null=True)
user = models.CharField(max_length = 50, unique = True, null=True)
hobby = models.CharField(max_length = 50, null=True)
job = models.CharField(max_length = 60, null=True)
class Trial(CsvModel):
rubbish = DecimalField()
user = CharField()
hobby = CharField()
class Meta:
dbmodel = Profile
delimiter = ','
has_header = True
Error message is as follows:
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/pangkachun/Desktop/smallpro2/small_pro/small/models.py", line 2, in <module>
from adaptor.model import CsvModel
File "/usr/local/lib/python3.6/site-packages/adaptor/model.py", line 269
except ValueError, e:
^ . `
You are using python3.6 but the library looks like it is made for python2.5-
For Python 3 it should be
except ValueError as e:
source
You may have to find a different csv plugin like django-csvimport and possibly change your strategy accordingly
My app is installed correctly and its models.py reads:
from django.db import models
class Album(models.Model):
artist = models.CharField(max_lenght=250)
album_title = models.CharField(max_lenght=500)
genre = models.CharField(max_lenght=100)
album_logo = models.CharField(max_lenght=1000)
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_lenght=10)
song_title = models.CharField(max_lenght=250)
But whenever I run python manage.py migrate, I get the following error:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 371, in execute_from_command_line
utility.execute()
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 347, in execute
django.setup()
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 3, in <module>
class Album(models.Model):
File "C:\Users\dougl\desktop\django websites\twenty_one_pilots\downloads\models.py", line 4, in Album
artist = models.CharField(max_lenght=250)
File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\db\models\fields\__init__.py", line 1042, in __init__
super().__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'max_lenght'
What could be wrong? I'm still a beginner and I'm still learning about databases.
Use this:
As per my comment, length (lenght) splelling is wrong.
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.TextField()
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
You have spelled length wrong here
album_title = models.CharField(max_lenght=500)
happens to the best of us.
I have problems with circularity in my two files. Model import function to run when create object and this function import model to check if code in unique.
How use model in function and function in model without problem with circularity? I checked questions simillar to my problem but i still don't know to fix this issue.
models.py
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from .middleware.current_user import get_current_user
from shortener.utils import create_shortcode
from django.conf import settings
CODE_MAX_LENGTH = getattr(settings, 'CODE_MAX_LENGTH', 16)
class Shortener(models.Model):
url = models.URLField()
code = models.CharField(unique=True, blank=True, max_length=CODE_MAX_LENGTH)
author = models.ForeignKey(User, blank=True, null=True) # Allow anonymous
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
def save(self, *args, **kwargs):
if not self.pk:
self.author = get_current_user()
if self.code in [None, ""]:
self.code = create_shortcode()
elif self.code.find(' ') != -1:
self.code = self.code.replace(' ', '_')
if self.url not in ["http", "https"]:
self.url = "http://{0}".format(self.url)
super(Shortener, self).save(*args, **kwargs)
def __str__(self):
return self.url
def __unicode__(self):
return self.url
def get_short_url(self):
return reverse("redirect", kwargs={'code': self.code})
Utils.py
import random
import string
from django.conf import settings
from shortener.models import Shortener
SIZE = getattr(settings, 'CODE_GENERATOR_MAX_SIZE', 12)
def code_generator(size=SIZE):
return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(size))
def create_shortcode():
code = code_generator()
if Shortener.objects.filter(code=code).exists():
create_shortcode()
return code
Traceback:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x037EAB28>
Traceback (most recent call last):
File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\loc\shortener\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\loc\shortener\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\loc\shortener\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\loc\shortener\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\loc\shortener\lib\site-packages\django\apps\config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "E:\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\Users\loc\PycharmProjects\DjangoURLShortener\shortener\models.py", line 4, in <module>
from shortener.utils import create_shortcode
File "C:\Users\loc\PycharmProjects\DjangoURLShortener\shortener\utils.py", line 4, in <module>
from shortener.models import Shortener
ImportError: cannot import name 'Shortener'
Short answer: Move the create_shortcode implementation into the models.py module, it's just 3 lines of code to generate codes in there and you avoid the circular imports. Do the filters inside the model and Shortener.save method with self.objects.filter(...).
Longer answer: The uuid module and the uuid.uuid4 function is better (than writing a possibly buggy implementation yourself) for generating unique codes. You are, at the moment, generating 12-character or 12-byte random codes, and the UUID module can generate 16-byte codes for you out of the box. If you want enable user-definable or overridable codes but wish to generate very unique codes automatically:
code = models.CharField(unique=True, max_length=16, default=uuid.uuid4)