Can anyone help me fix why category names are not displaying in my admin console? I am trying to use smart_selects but it seems as though something is not setup correctly. I am using django 1.9, python 2.7
Here is my models.py
from __future__ import unicode_literals
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
class Category (models.Model):
category = models.CharField(max_length = 255)
def _unicode_(self):
return self.category
class Brand (models.Model):
brand = models.ForeignKey(Category)
def _unicode_(self):
return self.brand
class Make (models.Model):
category = models.ForeignKey(Category)
brand = ChainedForeignKey(Brand, chained_field = 'category',
chained_model_field = 'category', show_all = False, auto_choose = True)
Here is my admin.py
from django.contrib import admin
from .models import Category, Brand, Make
admin.site.register(Category)
admin.site.register(Brand)
admin.site.register(Make)
I have the app registered in settings
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'smart_selects',
'app',
'blog',
]
But here is how it looks in Admin console
Your function name is wrong. It's __unicode__ with 2 underscores not one.
Related
I am trying to register my custom user model to the admin site (I have name my custom user model User), but I am getting this error.
as I understood that I should unregister the original User model then register my custom model and this what I have tried to do!!
---------setings.py-------
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users', # This is custom user model
]
AUTH_USER_MODEL = 'users.User'
---------users/admin.py-------
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User as MyUser # my Custom User Model
from django.contrib.auth.models import User
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
list_display = ('username', 'email')
admin.site.register(MyUser,MyUserAdmin)
You need to modify INSTALLED_APPS block
You need add below string Instead of just "users"
**'users.apps.UsersConfig'**
Users- your app name
apps - one file would be created in your app folder
Userconfig - config function in your apps.py file.
this error disappear by importing PermissionsMixin and pass it to my custom user model class as a second argument in model.pyfile and it worked
from django.contrib.auth.models import PermissionsMixin
class User(AbstractBaseUser,PermissionsMixin):
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(max_length=100, unique=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
I am trying to create a multi tenant app (with shared database and isolated schema) using this Django-Tenants package.
And I've followed the example videos to setup a demo: video1 and video2
app clients (models.py)
from django.db import models
from django_tenants.models import TenantMixin, DomainMixin
class Client(TenantMixin):
name = models.CharField("Customer name", max_length=100)
created_on = models.DateField(auto_now_add=True)
# default true, schema will be automatically created and synced when it is saved
auto_create_schema = True
class Domain(DomainMixin):
pass
app sweet_tenant (models.py)
from django.db import models
from applications.sweet_shared.models import SweetType
class Sweet(models.Model):
sweet_type = models.ForeignKey(SweetType, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
price = models.DecimalField(default=0, decimal_places=3, max_digits=8)
def __str__(self):
return self.name
app sweet_shared (models.py)
from django.db import models
class SweetType(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
settings
# Application definition
SHARED_APPS = [
"django_tenants", # mandatory
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# shared apps
"applications.clients",
"applications.sweet_shared",
]
TENANT_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# your tenant-specific apps
"applications.sweet_tenant",
)
INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS]
BEHAVIOUR
Public schema are shared with all tenants. Any tenant can see any data form public schema if you don't filter. This is a normal behavior
Tenants (clients) are created in the public schema.
NEEDS
I dont want that these data (tenants) can be seen by any tenant, because it will contain private client data. Each tenant only needs to see his data and only the SaaS owner can see all data (superuser in public schema).
PROBLEM
I have added this code (see code below) into the admin.py file to filter tenant's data. This works fine. But the problem is that I have not been able to detect when it is not a tenant and is the superuser of the public schema. Or is there a better way to achieve it?
from django.contrib import admin
from django_tenants.admin import TenantAdminMixin
from django.db import connection
from .models import Client
class ClientAdmin(TenantAdminMixin, admin.ModelAdmin):
list_display = (
"name",
"schema_name",
"created_on",
)
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return self.readonly_fields + ('schema_name', 'created_on')
return self.readonly_fields
def get_queryset(self, request):
qs = super().get_queryset(request)
return qs.filter(name=connection.tenant)
admin.site.register(Client, ClientAdmin)
You can add the following Mixin to the ClientAdmin to only allow public tenants to see your clients and domains data.
from django.contrib import admin
from django_tenants.admin import TenantAdminMixin
from django_tenants.utils import get_public_schema_name
from backend.customers.models import Client, Domain
class PublicTenantOnlyMixin:
"""Allow Access to Public Tenant Only."""
def _only_public_tenant_access(self, request):
return True if request.tenant.schema_name == get_public_schema_name() else False
def has_view_permission(self,request, view=None):
return self._only_public_tenant_access( request)
def has_add_permission(self,request, view=None):
return self._only_public_tenant_access(request)
def has_change_permission(self,request, view=None):
return self._only_public_tenant_access( request)
def has_delete_permission(self,request, view=None):
return self._only_public_tenant_access( request)
def has_view_or_change_permission(self,request, view=None):
return self._only_public_tenant_access( request)
#admin.register(Client)
class ClientAdmin(PublicTenantOnlyMixin,TenantAdminMixin, admin.ModelAdmin):
list_display = ('name', 'paid_until')
#admin.register(Domain)
class DomainAdmin(PublicTenantOnlyMixin,TenantAdminMixin, admin.ModelAdmin):
list_display = ('domain',)
I'm trying to customize auth backend while customized auth model but keep facing this error because i'm using get_user_model() function.
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'base.User' that has not been installed
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base.apps.BaseConfig',
'core.apps.AccountsConfig',
'system.apps.SystemConfig',
]
custom Backend:
class UserBackend(object):
def authenticate(self, request, username=None, password=None, **kwargs):
usermodel = User
try:
usr = usermodel.objects.get(username=username)
password_valid = usr.check_password(password)
if usr and password_valid:
return usr
raise PermissionDenied
except usermodel.DoesNotExist:
return PermissionDenied
return None
def get_user(self, user_id):
usermodel = User
try:
return usermodel.objects.get(pk=user_id)
except usermodel.DoesNotExist:
return None
Edit:
settings:
AUTH_USER_MODEL = 'base.User'
AUTHENTICATION_BACKENDS = (
'base.models.UserBackend',
)
base.User model:
class User(AbstractUser):
fullname = models.CharField(max_length=35, null=True, blank=True)
picture = models.ManyToManyField('ImageFile', verbose_name="ProfilePicture", blank=True)
bio = models.CharField(max_length=255, null=True, blank=True)
link = models.URLField(null=True, blank=True, default="")
is_private = models.BooleanField(default=False)
is_official = models.BooleanField(default=False)
Note: UserBackend is on the end of file and class User(AbstractUser) is above it
There was an import in base.models file, from django.contrib.auth.backends import ModelBackend which caused this error even when i removed custom AUTHENTICATION_BACKENDS.after i removed this import, everything works fine although i moved backend class from base.models to backend file in the base app (i think its not necessary, i just did it for more readable codes)
For me it was the same. It took me over an hour to find out that you cannot have the CustomBackend(BaseBackend) and the CustomUser(AbstractUser) in the models.py of your app. This info is nowhere to be found in the official Django docs.
Django Version: 3.1.2
Python Version: 3.8.2
models.py of the app "Users":
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
auth.py (arbitrary name, living in the "Users" app):
from django.db import models
from django.contrib.auth.backends import BaseBackend
class UserAuth(BaseBackend):
def authenticate(self, request, username, password):
pass
def get_user(self, user_id):
pass
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig'
]
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = [
'users.auth.UserAuth'
]
I'm a Python/Django noob. So any help will be appreciated.
Trying to use the django-fluent-contents
models.py
from django.core.urlresolvers import reverse
from django.db import models
from fluent_contents.models.fields import PlaceholderField, PlaceholderRelation, ContentItemRelation
from fluent_contents.models import ContentItem
class Article(models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField("Slug", unique=True)
content = PlaceholderField("article_content")
placeholder_set = PlaceholderRelation()
contentitem_set = ContentItemRelation()
class Meta:
verbose_name = "Article"
verbose_name_plural = "Articles"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('article-details', kwargs={'slug': self.slug})
admin.py
from django.contrib import admin
from article.models import Article
from fluent_contents.admin import PlaceholderFieldAdmin
class ArticleAdmin(PlaceholderFieldAdmin):
prepopulated_fields = {'slug': ('title',)}
fieldsets = (
(None, {
'fields': ('title', 'slug', ),
}),
("Contents", {
'fields': ('content',),
'classes': ('plugin-holder',),
})
)
admin.site.register(Article, ArticleAdmin)
I'm using South for migration.
db.create_table(u'article_article', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=200)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)),
))
db.send_create_signal(u'article', ['Article'])
It looks like, no column is being created for the 'content' field.
So when I try to add a new 'Article' via django admin —
FieldError at /manage/article/article/add/
Unknown field(s) (content) specified for Article. Check fields/fieldsets/exclude attributes of class ArticleAdmin.
If I remove the fieldset from admin.py
class ArticleAdmin(PlaceholderFieldAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Article, ArticleAdmin)
The 'content' field is not shown in django admin
In reply to #vdboor.. Here's my installed apps ...
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
# 3rd party apps
'south',
'django_extensions',
'compressor',
'debug_toolbar',
'fluent_contents',
'fluent_contents.plugins.text',
'django_wysiwyg',
# Project specific apps go here
'article',
)
Also I'm using the example app from the repo as a guide... just removed the extra plugin model
FYI I'm using
Django==1.6
MySQL-python==1.2.4
South==0.8.4
Thank you for all the help :-)
It looks like, no column is being created for the 'content' field.
That is correct, the PlaceholderField becomes a reverse-generic-relation.
You can try removing the fieldsets declaration for now, and see what other error you get.
The repository also contains an example application, which you can run, and compare with your app.
Silly question, but is fluent_contents in the INSTALLED_APPS?
Still need to add extra fields. In the example shown, because the content is stored in a separate table - model ContentItem.
from fluent_contents.models.fields import PlaceholderField, PlaceholderRelation, ContentItemRelation
class Article(models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField("Slug", unique=True)
content = PlaceholderField("article_content")
placeholder_set = PlaceholderRelation() # <-- this
contentitem_set = ContentItemRelation() # <-- and this
class Meta:
verbose_name = "Article"
verbose_name_plural = "Articles"
django 1.5.1
I create custom auth model:
file api/models.py
from django.contrib.auth.models import BaseUserManager, AbstractUser
class User(AbstractUser):
token = models.CharField(max_length=64, null=False, blank=False, help_text=_('Photo for carte'), unique=True)
updated_token = models.DateTimeField(auto_now_add=True, help_text=_('Create record'))
USERNAME_FIELD = 'email'
objects = MyUserManager()
def __unicode__(self):
return "пользователь: %s" % self.email
class Meta:
app_label = 'custom_auth'
file settings.py
AUTH_USER_MODEL = 'custom_auth.User'
.....
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
.....
'south',
'django.contrib.admin',
)
on ./manage.py syncdb I get an error:
admin.logentry: 'user' has a relation with model <class 'api.models.User'>, which has either not been installed or is abstract.
How decide this problem?
Edit 1
tried comment line and make syncdb:
'django.contrib.admin',
syncdb was successful
after that tried create user in ./manage.py shell
In [1]: from api.models import User
In [2]: User.objects.create_superuser('test#test.com', 'test')
and recieve error:
DatabaseError: (1146, "Table 'app_name.custom_auth_user' doesn't exist")
You will need to set an app_label on your class which is also in your INSTALLED_APPS: either set app_label = 'api' (the default), or add 'custom_auth' to your INSTALLED_APPS (of course, it needs to be a valid app then).
The validation process in Django tries to get the new User class using get_model, and by default get_model returns models for installed apps only. You can verify with your current code:
>>> loading.get_model('custom_auth', 'user')
>>> loading.get_model('custom_auth', 'user', only_installed=False)
> api.models.User
You forgot to add your Meta app_label description to the INSTALLED_APPS:
# Application definition
INSTALLED_APPS = (
...
'custom_auth',
)