Sorl thumbnail not showing thumb in AdminImageMixin - django

I'm having trouble with Django 1.3 using django-grappeli and sorl-thumbnail.
I have a project that uses this code from the official sorl-thumbnails docs:
# myapp/admin.py
from django.contrib import admin
from myapp.models import MyModel
from sorl.thumbnail.admin import AdminImageMixin
class MyModelAdmin(AdminImageMixin, admin.ModelAdmin):
pass
This project works well with the debug server and a nice little thumbnail appears in the change form of the admin.
However, in another project, i'm serving my project through WSGI and I have 3 separate domains:
www.example.com
media.example.com (that's serving user uploaded files)
static.example.com (that's serving static files)
However, in this project, the AdminImageMixin works fine except no thumbnail is available in the changeform for a model:
It uploads the picture in the correct place
It puts the correct text in the database field (uploads/ + picture_name.jpg) (i verified this with phpmyadmin)
It doesn't show any thumbnail in the form besides the browse button (like i'm used to)
Here is some sample code:
# models.py
class Category(models.Model):
name = models.CharField(max_length=200, verbose_name='name', help_text='Name of category')
description = models.TextField(verbose_name='Description', help_text='You can use Textile')
icon = ImageField(upload_to='uploads/', blank=True, null=True)
# admin.py
class CategoryAdmin(AdminImageMixin, admin.ModelAdmin):
pass
admin.site.register(Category, CategoryAdmin)
# settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'grappelli',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
'django_evolution',
'django_extensions',
'sorl.thumbnail',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
Any ideea what I'm doing wrong?
Thank you in advance.

Did you remember to put the sorl.thumbnail in your INSTALLED_APPS and sync the database after it. In case you didn't there isn't a table for the key value pairs and it wont work. I suppose you are using the default database as your key value storage, not redis.

I run into the same problems, turns out the PIL I installed didn't have jpeg support to make the actual thumbnails although it never showed any error.
This is how I fixed it:
install jpeg support
sudo apt-get install libjpeg libjpeg-dev
On MAC:
brew install jpeg
reinstall PIL
pip install -I PIL
After recompiling it should show that the jpeg support is available, refresh your admin page and you should see the thumbnails.

Check with a debugger if the form field is using the correct widget.
I had the same problem when i was inheriting from 3 different admin classes:
django-mptt : MPTTModelAdmin
django-modeltranslation : TranslationAdmin
sorl-thumbnail : AdminImageMixin
I'm pretty sure that (in my case) django-modeltranslation is overriding the behaviour of sorl-thumbnail changing the "widget" attribute of the ImageField field from AdminImageWidget.
I forced the widget to AdminImageWidget on the get_form function like this:
def get_form(self, request, obj=None, **kwargs):
kwargs = self._do_get_form_or_formset(request, obj, **kwargs)
form = super(CategoryAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['background'].widget = AdminImageWidget()
return form
At this point using the mixing AdminImageMixin is optional.

./manage.py makemigrations thumbnail
./manage.py migrate thumbnail
If you get permission issue look at
https://stackoverflow.com/a/41541666

Related

Impossible to use django-allauth when there is already an `account` app?

My Django application already has an app called account. Does it mean that it is ABSOLUTELY impossible to use django all-auth because of the name conflict? Due to the existing data, the app account cannot be renamed.
settings.py:
INSTALLED_APPS = [
...
'account',
...
# For allauth:
'django.contrib.sites',
'allauth',
'allauth.account', # Name conflict
...
If so, is there a good alternative?
2-14
Per solarissmoke's suggestion. Where should I put the new app and what is it name?
Is it something like this (Of course, it is wrong)?
my_project/account/apps.py:
import allauth.account
from django.apps import AppConfig
class AccountConfig(AppConfig):
name = 'account'
class AllAuthAccountConfig(allauth.account):
name = 'allauth.account'
label = 'allauth_account' # Change this
verbose_name = 'aullauth_account'
This is a known problem with django-allauth.
You can work around it by changing your own app to use a different app label. In your app's AppConfig:
class AccountConfig(AppConfig):
name = 'my_project.apps.account'
label = 'my_project_account' # Change this
verbose_name = 'account'
And refer to this app config in your INSTALLED_APPS, e.g.,
INSTALLED_APPS = [
...
'account.apps.AccountConfig',
...
'allauth',
'allauth.account',
...
Which should now work because the app labels are unique. Note that the only issue with this is that database tables names for your account app will have to change so as not to conflict with the allauth app - this will require some data migrations (if on an established project) or creation of fresh migrations (if on a project where you can afford to clobber the database).
You can also do this with the allauth.account app if that's easier - just create a new app config anywhere in your project, e.g.,
my_project/allauth_apps/apps.py (make sure to also create __init__.py in this new directory):
class AllAuthAccountConfig(allauth.account):
name = 'allauth.account'
label = 'allauth_account' # Change this
verbose_name = 'aullauth_account'
And then in your INSTALLED_APPS replace account with my_project.allauth_apps.apps.AllAuthAccountConfig. As above, this changes the database table names.
you need to fork the git on your own and change the label
fork the source code from https://github.com/pennersr/django-allauth/
add unique label such as allauthaccount to app in django-allauth/allauth/account/apps.py on your own forked git
commit
add following line to your requirements.txt -e git+https://github.com/andylee0213/django-allauth#egg=django_allauth
do "pip install -r requirements.txt and pip freeze > requirements.txt" and check github link is still in requirements.txt
but my suggestion is, instead of not receiving updates and going through all this pain, just use other auth libraries. There are many other libraries that does not depend on all auth. check
https://medium.com/codex/django-allauth-vs-dj-rest-auth-vs-python-social-auth-vs-drf-social-oauth2-ef7d50f92d16

Error after adding Django channels to installed_apps in settings file

I am just trying out django channels so I created a virtual environment and installed django, drf and channels. It threw error asking for visual c++ build tools which got resolved after installing it. Then I created a channels project and an app. Then just for testing I added a sample model as below and registered it with the admin. It compiled well and also I was able to see the model in the admin page.
My Model Calss
from django.db import models
# Create your models here.
class College(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=150)
objects = models.Manager()
def __str__(self):
return self.name
My admin.py
from django.contrib import admin
from .models import College
# Register your models here.
admin.site.register(College)
Now the Problem
I added channels to the INSTALLED_APPS list in the settings.py file like below,
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channelApp',
'channels',
]
Now when I try to run the server using the runserver command I get the following error
ModuleNotFoundError: No module named 'win32api'
LookupError: No installed app with label 'admin'.
I have been searching but failed to find any suitable answer. Kindly help me out.
Thanks in advance.
Just after I posted this I stumbled onto a SO post
Issue after installing django channels
Just to reiterate in short, this is an open bug and the work around is to install the following package
pip install pypiwin32
After installing you may have to close and reopen the editor for the changes to reflect. And the error is resolved.

django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: thumbnail

I am developing a django web project that uses the following packages/applications:
sorl-thumbnail
django-oscar
Here is a snippet of my settings.py file:
INSTALLED_APPS = [
'registration', #should be immediately above 'django.contrib.auth'
'django.contrib.auth',
# ...
'zinnia',
'zinnia_tinymce',
'sorl.thumbnail',
'embed_video',
# ...
'django.contrib.flatpages',
'compressor',
'widget_tweaks',
] + get_core_apps()
When I comment out sorl.thumbnail, I am able to run the development server using manage.py runserver. However, if I uncomment the sorl.thumbnail line and try to run the development server, it throws an exception:
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: thumbnail
Now, I am aware that a similar question exists on this site, however, following the instructions in the accepted solution, i.e.:
create a sol_thumbnail folder in same directory as the manage.py script
create sorl_thumbnail/apps.py (see below)
modify myproject/mysite/___init____.py (see below)
sorl-thumbnail/apps.py
from django.apps import AppConfig
class SorlthumbnailConfig(AppConfig):
name = 'sorl-thumbnail'
label = 'sorl.thumbnail'
myproject/mysite/_init _.py
default_app_config = 'sorl-thumbnail.apps.SorlthumbnailConfig'
Why is the fix above not working, and how do I resolve this issue?
BTW: I am using django-1.10
I went though the same problem of duplicated applications, and following exactly the similar question I solved my problem.
The problem with your solution is that you have added default_app_config = 'sorl-thumbnail.apps.SorlthumbnailConfig' to myproject/mysite/___init____.py, but you should have added to myproject/sorl-thumbnail/___init____.py.

Django tutorial part 2 - app does not show up on admin after registering

Following the Django tutorial (part 2), I can't seem to see my Polls app in my django admin panel after registering it. My screen looks a bit like this, with a distinct lack of a section for the Polls app:
What I've done so far (following parts of this answer and the tutorial itself):
Registered my app in the admin.py file.
Added it to INSTALLED_APPS in settings.py in my project folder.
Ran python manage.py makemigrations & python manage.py migrate without any changes (btw, for future readers - that's the new >1.8 incarnation of syncdb, I believe).
Made sure the user I'm signing in with has superuser priviliges (as per this answer).
Restarted my nginx.
I'm still hazy as to what the problem is or, for that matter, how to debug it.
My admin.py file:
from django.contrib import admin
from .models import Question
admin.site.register(Question)
My models.py file (notice the Question object):
import datetime
from django.utils import timezone
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
INSTALLED_APPS portion of my settings.py project file:
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
As it turns out, I wasn't paying attention to the process in which the application was served.
So, riding on this answer, I figured out it breaks down like this:
nginx gets a URL, decides where to pull from - in our case, Gunicorn.
Gunicorn searches for the proper Python file to pull - in our case, Django.
Djnago gets executed and the app loads (including our admin panel).
In this case, after making the changes to the admin panel I've restarted nginx, but not Gunicorn. Restarting Gunicorn solved the problem, and if you looked at my last comment - nginx crashed because of a typo in my admin.py file (added well after writing this question, during my attempt to fix it, and thus does not appear in the OP).

RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS

I am building an application with Django Rest Framework and AngularJs. I am using Django-rest-auth for my authentication purposes, although, I have not been able to set it up. Anyway, I am trying to set up this app with my project. I realized I need to install django-rest-auth-registration to get it running, so I followed this documentation to do the following things:
I ran the commands
pip install django-rest-auth
and
pip install django-allauth
Any my settings.py looks like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party apps
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'allauth',
'allauth.account',
'rest_auth.registration',
# My app
'myapp',
]
I have also added the authentication backends, context_processors, and the proper urls.
However, when I try to migrate, my terminal throws the following error:
RuntimeError: Model class django.contrib.sites.models.Site doesn't
declare an explicit app_label and isn't in an application in
INSTALLED_APPS.
Why do I get this error, and how do I solve it to migrate my project? Thanks!
The fix
Just add Django's Sites framework to your apps and set SITE_ID to 1 in your settings.
INSTALLED_APPS = [
...
'django.contrib.sites',
]
SITE_ID = 1
Why does this happen?
Django's Sites Framework is a contributed module bundled with the core library that allows for the use of a single Django application/codebase with different sites (that can use different databases, logic in views, etc). The SITE_ID setting, as stated in the docs, "is used so that application data can hook into specific sites and a single database can manage content for multiple sites."
In this particular case AllAuth requires the Sites Framework in order to function properly. Many other third-party libraries are built to safely handle cases where multiple sites may be present and as such may be best .
I landed on this post via Google search. My problem was running tests that blew up with the error:
RuntimeError: Model class app.taxonomy.models.Term doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
This was running on Python 2.7.x with absolute imports. As mentioned by Colton Hicks in the comments, below, this can also happen with Python 3 (pytest 3.2.3 with Django 1.11.4).
In my tests.py:
from __future__ import absolute_import
[...]
from .models import Demographics, Term
After changing the relative import to an absolute import the problem went away:
from taxonomy.models import Demographics, Term
HTH
Try adding the app_label = 'yourApp' in the models Meta class:
class Meta:
app_label = 'yourApp'
I got the error above. However my problem was the in the urls.py. I was following PyDanny cookiecutter django recipe. My error was to put in the urls.py this line:
url(r'^demo/', include('project.demoapp.urls', namespace='demoapp')),
when I corrected to this:
url(r'^demo/', include('demoapp.urls', namespace='demoapp')),
all was well. I also changed my local apps (I did this first and so the critical error was the url misconfiguration):
LOCAL_APPS = [
# Your stuff: custom apps go here
'demoapp.apps.DemoAppConfig',
]
I have django debug toolbar installed and this was actually causing the/my problem.
INSTALLED_APPS (in settings.py) needs the entry 'django.contrib.sessions'. Make sure to run migrate after adding.
Just add 'django.contrib.sites', to INSTALLED_APPS and set SITE_ID = 1 in your settings.py file.
Upgraded Answer for Django>=4.0 // 2022
Add Django's Sites framework and FlatPages Framework to your INSTALLED_APPS and set SITE_ID in your settings.
INSTALLED_APPS = [
...
'django.contrib.sites',
'django.contrib.flatpages',
]
SITE_ID = 1
Your tests should work like a charm
This error occurred because I had created a new app folder for a subset of sites related to another feature. This needed to be added to my INSTALLED_APPS in settings.py
Django 4.1+ (2023)
After almost an hour digging, what solved for me was this:
INSTALLED_APPS = [
...
'django.contrib.sessions',
]
No need for SITE_ID or additional INSTALLED_APPS entries.
Everything worked as expected after I made a migration
python manage.py migrate
Good luck