Django: url instead of image in Admin - django

I need to show a image preview (small size image) of my order_item in admin.
I'm basically following these other question/answer here:
Django Admin Show Image from Imagefield
However, I cannot get the desired results. I'm getting this instead:
I though it was maybe the URL, but the relative path of that file is the same (except for the static part):
static/media/images/python.png
What could be wrong?
models.py:
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.CharField(max_length= 200)
quantity = models.CharField(max_length= 200)
size = models.CharField(max_length=200)
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price')
image = models.ImageField(upload_to='images', blank=True, null=True)
comment = models.CharField(max_length=200, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "OrderItem"
def image_thumbnail(self):
return u'<img src="%s" />' % (self.image.url)
image_thumbnail.short_description = 'Image Thumbnail'
image_thumbnail.allow_tags = True
def sub_total(self):
return self.quantity * self.price
admin.py
# Register your models here.
class OrderItemAdmin(admin.TabularInline):
model = OrderItem
fieldsets = [
# ('Customer', {'fields': ['first_name', 'last_name'], }),
('Product', {'fields': ['product'],}),
('Quantity', {'fields': ['quantity'],}),
('Price', {'fields': ['price'], }),
('Image', {'fields': ['image'], }),
('Image_Thumbnail', {'fields': ['image_thumbnail'], }),
]
readonly_fields = ['product', 'quantity', 'price', 'image', 'image_thumbnail']
can_delete = False
max_num = 0
template = 'admin/order/tabular.html'
### Order Display ###
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
model = Order
list_display = ['id', 'first_name', 'last_name', 'email', 'total', 'reason', 'created']
list_editable = ['reason',]
list_display_links = ('id', 'email')
search_fields = ['token', 'shipping_department', 'email']
readonly_fields = ['id','created']
fieldsets = [
('ORDER INFORMATION', {'fields': ['id','token', 'total', 'created']}),
# ('BILLING INFORMATION', {'fields': ['billingName', 'billingAddress1', 'billingCity', 'billingPostCode',
# 'billingCountry', 'emailAddress']}),
('SHIPPING INFORMATION', {'fields': ['first_name', 'last_name', 'shipping_address', 'shipping_department', 'shipping_province',
'shipping_district', 'shipping_address1', 'shipping_address2']}),
]
inlines = [
OrderItemAdmin,
]
def has_delete_permission(self, request, obj=None):
return False
def has_add_permission(self, request):
return False

From Django 1.9, allow_tags has been deprecated, instead you can use mark_safe:
From documentation:
In older versions, you could add an allow_tags attribute to the method to prevent auto-escaping. This attribute is deprecated as it’s safer to use format_html(), format_html_join(), or mark_safe() instead.
So, try like this:
from django.utils.html import mark_safe
...
def image_thumbnail(self):
return mark_safe('<img src="%s" />' % (self.image.url))

Related

How to fix django admin "add" button

I'm new to web development, and i'm building a blog web app in Django.
I'm having problems adding new posts through django-admin. Clicking the "add" button gives me an "Error during template rendering - 'str' object has no attribute 'utcoffset'" error message.
models.py
from django.db import models
from django.utils import timezone
import datetime
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(blank=True, null=True)
post_date = models.DateTimeField(default='date posted')
def published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.post_date <= now
published_recently.admin_order_field = 'post_date'
published_recently.boolean = True
published_recently.short_description = 'Recent post?'
def __str__(self):
return self.title
class Customer(models.Model):
username = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.CharField(max_length=50)
country = models.CharField(max_length=50)
reg_date = models.DateTimeField(default='date reg')
def __str__(self):
return self.username
class Comment(models.Model):
comment_cont = models.TextField(max_length=200)
user_name = models.ForeignKey(Customer, default=0, on_delete=models.CASCADE)
comment_post = models.ForeignKey(Post, on_delete=models.CASCADE)
votes = models.BigIntegerField(default=0)
comment_date = models.DateTimeField(default='date commented')
def __str__(self):
return self.comment_cont
class Feedback(models.Model):
feedback_title = models.CharField(max_length=50)
feedback_detail = models.CharField(max_length=200)
user_name = models.ForeignKey(Customer, default=1, verbose_name='user_name', on_delete=models.SET_DEFAULT)
admin.py
from django.contrib import admin
from .models import Post, Customer, Feedback, Comment
# Register your models here.
class CommentInLine(admin.TabularInline):
model = Comment
extra = 1
fields = ['comment_cont', 'votes', 'comment_date']
class CustomerAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['firstname', 'lastname', 'username', 'email', 'country', 'reg_date']})
]
class PostAdmin(admin.ModelAdmin):
fieldsets = [
('Post', {'fields': ['title', 'content']}),
('Date information', {'fields': ['post_date'], 'classes':['collapse']}),
]
inlines = [CommentInLine]
list_display = ('title', 'content', 'post_date', 'published_recently')
list_filter = ['post_date']
search_fields = ['title']
class FeedbackAdmin(admin.ModelAdmin):
fieldsets = [
('Feedback', {'fields': ['feedback_title', 'feedback_detail', 'user_name']}),
]
list_display = ('user_name', 'feedback_title', 'feedback_detail')
# inlines = [CustomerInLine]
# list_display = ('user_name', 'feedback_title', 'feedback_detail')
class CommentAdmin(admin.ModelAdmin):
fields = ['user_name', 'comment_post', 'comment_cont', 'votes', 'comment_date']
admin.site.register(Post, PostAdmin)
admin.site.register(Feedback, FeedbackAdmin)
admin.site.register(Customer, CustomerAdmin)
admin.site.register(Comment, CommentAdmin)
I want to be able to add posts through Django admin. Any other corrections to the code is highly welcome. I appreciate the help. Thanks.
post_date = models.DateTimeField(default='date posted')
the post_date is DateTimeField and you have provided a string as default . It should be an instance of datetime.datetime.
post_date = models.DateTimeField(default=timezone.now)
# or
post_date = models.DateTimeField(auto_now_add=True, verbose_name='Publish Time')
should fix the problem

Django: Admin fields not editable?

I imported a project from Django builder, managed to install the dependencies, and start the admin, but I have an issue.
All of the fields in admin are not editable! None of them.
Here's a screenshot of the issue:
Here's the relevant files:
Admin.py
from django.contrib import admin
from django import forms
from .models import Tours, Locations, Photos, PlaceLocations, Information
class ToursAdminForm(forms.ModelForm):
class Meta:
model = Tours
fields = '__all__'
class ToursAdmin(admin.ModelAdmin):
form = ToursAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Tags', 'Photo', 'Description', 'Duration']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Tags', 'Photo', 'Description', 'Duration']
admin.site.register(Tours, ToursAdmin)
class LocationsAdminForm(forms.ModelForm):
class Meta:
model = Locations
fields = '__all__'
class LocationsAdmin(admin.ModelAdmin):
form = LocationsAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Photo', 'MainLocLat', 'MainLocLon', 'MainLocRad', 'Audio', 'Description']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo', 'MainLocLat', 'MainLocLon', 'MainLocRad', 'Audio', 'Description']
admin.site.register(Locations, LocationsAdmin)
class PhotosAdminForm(forms.ModelForm):
class Meta:
model = Photos
fields = '__all__'
class PhotosAdmin(admin.ModelAdmin):
form = PhotosAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Photo']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo']
admin.site.register(Photos, PhotosAdmin)
class PlaceLocationsAdminForm(forms.ModelForm):
class Meta:
model = PlaceLocations
fields = '__all__'
class PlaceLocationsAdmin(admin.ModelAdmin):
form = PlaceLocationsAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Latitude', 'Longitude', 'Radius']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Latitude', 'Longitude', 'Radius']
admin.site.register(PlaceLocations, PlaceLocationsAdmin)
class InformationAdminForm(forms.ModelForm):
class Meta:
model = Information
fields = '__all__'
class InformationAdmin(admin.ModelAdmin):
form = InformationAdminForm
list_display = ['name', 'slug', 'created', 'last_updated', 'Photo', 'Description']
readonly_fields = ['name', 'slug', 'created', 'last_updated', 'Photo', 'Description']
admin.site.register(Information, InformationAdmin)
models.py
from django.core.urlresolvers import reverse
from django_extensions.db.fields import AutoSlugField
from django.db.models import *
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_user_model
from django.contrib.auth import models as auth_models
from django.db import models as models
from django_extensions.db import fields as extension_fields
from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor
class Tours(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Tags = models.TextField(max_length=100)
Photo = models.ImageField(upload_to="/upload/images/")
Description = models.TextField(max_length=2000)
Duration = models.IntegerField()
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_tours_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_tours_update', args=(self.slug,))
class Locations(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Photo = models.ImageField(upload_to="/upload/images/")
MainLocLat = models.TextField(max_length=100)
MainLocLon = models.TextField(max_length=100)
MainLocRad = models.TextField(max_length=100)
Audio = models.FileField(upload_to="/upload/files/")
Description = models.TextField(max_length=2000)
# Relationship Fields
Photos = models.ForeignKey('app_name.Photos', )
PlaceLocations = models.ForeignKey('app_name.PlaceLocations', )
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_locations_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_locations_update', args=(self.slug,))
class Photos(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Photo = models.ImageField(upload_to="/upload/images/")
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_photos_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_photos_update', args=(self.slug,))
class PlaceLocations(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Latitude = models.TextField(max_length=100)
Longitude = models.TextField(max_length=100)
Radius = models.IntegerField()
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_placelocations_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_placelocations_update', args=(self.slug,))
class Information(models.Model):
# Fields
name = models.CharField(max_length=255)
slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
Photo = models.ImageField(upload_to="/upload/images/")
Description = models.TextField(max_length=2000)
class Meta:
ordering = ('-created',)
def __unicode__(self):
return u'%s' % self.slug
def get_absolute_url(self):
return reverse('app_name_information_detail', args=(self.slug,))
def get_update_url(self):
return reverse('app_name_information_update', args=(self.slug,))
You should better remove the readonly_fields attribute on each ModelAdmin class. Doing that, the fields, in the admin panel, will not be read-only!

How to Remove validation from left table data in django

2nd Screenshot of APIAPI Sample Screenshot
I'm New in Django, i want to help regarding validations in screenshot there is company_name, location, title and user_location fields except user info with proper validation
but i want to remove validations from company_name, location, title and user_location fields how to do?
Please find the above api screenshot and
Please find the below scripts,
views.py
class UserRegistrationView(generics.CreateAPIView):
"""
Register a new user.
"""
queryset = User.objects.all()
permission_classes = (permissions.AllowAny, )
def get_serializer_class(self, user_type=None):
if user_type == 'student':
return StudentRegistrationSerializer
return ProfessionalRegistrationSerializer
def post(self, request, user_type=None, format=None):
serializer_class = self.get_serializer_class(user_type)
serializer = serializer_class(data=request.data, context={'request': request})
if serializer.is_valid(raise_exception=True)
user = serializer.save(work_status=user_type)
token, created = Token.objects.get_or_create(user=user)
data = BasicUserSerializer(user, context={'request': request}).data
data.update({"token": token.key})
return Response(data)
serializes.py
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(max_length=20, write_only=True)
experiences = ExperienceSerializer(required=False)
email = serializers.EmailField()
first_name = serializers.CharField(max_length=30)
last_name = serializers.CharField(max_length=30)
class Meta:
model = User
fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
'experiences', 'headline')
def validate_email(self, value):
from validate_email_address import validate_email
if User.all_objects.filter(email=value.lower()).exists():
raise serializers.ValidationError('User with this email already exists.')
# if not validate_email(value.lower(), check_mx=True):
# raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
return value.lower()
def create(self, validated_data):
experiences = validated_data.pop('experiences')
password = validated_data.pop('password')
email = validated_data.pop('email')
user = User.objects.create(
username=email.lower(),
email=email.lower(),
role_id=1)
user.set_password(password)
user.save()
user_location = experiences.pop('user_location')
if hasattr(user, 'location'):
user.location.location = user_location
user.save()
else:
UserLocation.objects.create(user=user, location=user_location)
Experience.objects.create(user=user)
return user
Another serializes.py for Experiance
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
I want to Remove Validation from company_name, company, description, location, title, start_date, end_date, user_location
actually these fields are second page means after complete the first step users move on second step so second step fields are optional
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
def create(self, validated_data):
return Experience.objects.create(field_a='value', field_b='value')
in the above class, what should be do to remove validation of
"error_msg": {
"location": [
"Expected a dictionary of items but got type \"str\"."
],
"start_date": [
"Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
],
"end_date": [
"Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
],
"user_location": [
"Expected a dictionary of items but got type \"str\"."
]
}
Experience Model
class Experience(models.Model):
"""
"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='experiences')
company_name = models.CharField(max_length=200, db_index=True, blank=True)
company = models.ForeignKey('organisations.Organisation', null=True, blank=True, on_delete=models.SET_NULL)
description = models.TextField(null=True, blank=True)
location = models.ForeignKey('regions.Location', null=True, blank=True, on_delete=models.SET_NULL)
start_date = models.DateField(null=True, blank=True)
end_date = models.DateField(null=True, blank=True)
title = models.CharField(max_length=200, db_index=True, blank=True)
is_current = models.BooleanField(default=False)
is_associated = models.BooleanField(default=False)
created_at = models.DateTimeField(_('created at'), auto_now_add=True)
modified_at = models.DateTimeField(_('modified at'), auto_now=True)
class Meta:
db_table = 'experience'
verbose_name = _('experience')
verbose_name_plural = _('experiences')
ordering = ('-start_date',)
def __str__(self):
return getattr(self, 'title', '')
#property
def experience(self):
if self.end_date:
return (self.end_date - self.start_date).days
else:
return (datetime.datetime.now().date() - self.start_date).days
def get_formated_experience(self):
days = self.experience
total_months = round(days/30)
years = int(total_months/12)
months = round(((total_months/12)%1)*12)
year_txt = 'years' if years > 1 else 'year'
month_txt = 'months' if months > 1 else 'month'
return "%s %s %s %s" %(years, year_txt, months, month_txt)
Location Model
class Location(models.Model):
"""
"""
id = models.TextField(primary_key=True)
display_name = models.TextField(null=True, blank=True)
latitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
longitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
objects = LocationManager()
You are getting Two types of validation error according to snapshot.
Field is required
Expected a dictionary and got a string
The required field error occurs when you have set field as required in your model. You can change this by adding blank=True in your model for that field.
For second error, your serializer is expecting a dictionary and you are sending a string. You can remove this validation by writing your custom create method.
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
def create(self, validated_data):
# you create code for that models.
Your seriailzers will be like this
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(max_length=20, write_only=True)
experiences = ExperienceSerializer(required=False)
email = serializers.EmailField()
first_name = serializers.CharField(max_length=30)
last_name = serializers.CharField(max_length=30)
class Meta:
model = User
fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
'experiences', 'headline')
def validate_email(self, value):
from validate_email_address import validate_email
if User.all_objects.filter(email=value.lower()).exists():
raise serializers.ValidationError('User with this email already exists.')
# if not validate_email(value.lower(), check_mx=True):
# raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
return value.lower()
def create(self, validated_data):
experiences = validated_data.get('experiences')
password = validated_data.get('password')
email = validated_data.get('email')
user = User.objects.create(
username=email.lower(),
email=email.lower(),
role_id=1)
user.set_password(password)
user.save()
user_location = experiences.get('user_location')
location_object = None
if user_location:
location_object, created = Location.objects.get_or_create(display_name=user_location.get('display_name'), latitude= user_location.get('latitude'), longitude=user_location.get('longitude'))
user_experience = Experience.objects.create(user=user, company_name=experiences.get('company_name'), location=location_object)
return user
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')

How to add custom user model in admin panel?

I created a custom user model extending AbstractBaseUser class. code is below.
class UserModel(AbstractBaseUser):
sys_id = models.AutoField(primary_key=True, blank=True)
name = models.CharField(max_length=127, null=False, blank=False)
email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
mobile = models.CharField(max_length=10, unique=True, null=False, blank=False)
user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True, help_text="Admin(1)/Institute(2)/Student(3)")
access_valid_start = models.DateTimeField(null=True, blank=True)
access_valid_end = models.DateTimeField(null=True, blank=True)
created_when = models.DateTimeField(null=True, blank=True )
created_by = models.BigIntegerField(null=True, blank=True)
last_updated_when = models.DateTimeField(null=True, blank=True)
last_updated_by = models.BigIntegerField(null=True, blank=True)
notes = models.CharField(max_length=2048, null=True, blank=True)
is_active = models.BooleanField(default=True)
# this field is required to login super user from admin panel
is_staff = models.BooleanField(default=True)
# this field is required to login super user from admin panel
is_superuser = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = "email"
# REQUIRED_FIELDS must contain all required fields on your User model,
# but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
REQUIRED_FIELDS = ['name', 'mobile', 'user_type']
class Meta:
app_label = "accounts"
db_table = "users"
def __str__(self):
return self.email
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
# this methods are require to login super user from admin panel
def has_perm(self, perm, obj=None):
return self.is_superuser
# this methods are require to login super user from admin panel
def has_module_perms(self, app_label):
return self.is_superuser
Now in my admin panel only 'groups' is available. I want my custom user mode i.e. UserModel to appear in admin panel so that I can add, edit and delete user from admin user interface.
I tried multiple codes from SO, simplest of them is below
from django.contrib.auth.admin import UserAdmin
from accounts.models import UserModel
from django.contrib import admin
class MyUserAdmin(UserAdmin):
model = UserModel
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('mobile',)}),
)
admin.site.register(UserModel, MyUserAdmin)
now I am getting this errors ..
ERRORS:
<class 'accounts.admin.MyUserAdmin'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'groups', which is not an attribute of 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E019) The value of 'filter_horizontal[1]' refers to 'user_permissions', which is not an attribute of 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'MyUserAdmin', or an attribute or method on 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'MyUserAdmin', or an attribute or method on 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'last_name', which is not a callable, an attribute of 'MyUserAdmin', or an attribute or method on 'accounts.UserModel'.
<class 'accounts.admin.MyUserAdmin'>: (admin.E116) The value of 'list_filter[3]' refers to 'groups', which does not refer to a Field.
Please let me know how can I add custom user model successfully to admin UI?
From the Django Documentation
If your custom user model extends django.contrib.auth.models.AbstractUser, you can use Django’s existing django.contrib.auth.admin.UserAdmin class. However, if your user model extends AbstractBaseUser, you’ll need to define a custom ModelAdmin class. It may be possible to subclass the default django.contrib.auth.admin.UserAdmin; however, you’ll need to override any of the definitions that refer to fields on django.contrib.auth.models.AbstractUser that aren’t on your custom user class.
So basically, if you create a new user model from the AbstractBaseUser instead of AbstractUser you need to create your own custom ModelAdmin class, alternatively if you inherit from UserAdmin (which is what you're currently doing) you need to override and handle any differences.
#Anurag Rana your custom UserAdminclass should look like this
from django.contrib.auth.admin import UserAdmin
from accounts.models import UserModel
from django.contrib import admin
class MyUserAdmin(UserAdmin):
model = UserModel
list_display = () # Contain only fields in your `custom-user-model`
list_filter = () # Contain only fields in your `custom-user-model` intended for filtering. Do not include `groups`since you do not have it
search_fields = () # Contain only fields in your `custom-user-model` intended for searching
ordering = () # Contain only fields in your `custom-user-model` intended to ordering
filter_horizontal = () # Leave it empty. You have neither `groups` or `user_permissions`
fieldsets = UserAdmin.fieldsets + (
(None, {'fields': ('mobile',)}),
)
admin.site.register(UserModel, MyUserAdmin)
You are trying to use UserAdmin but you don't have fields which it refers to
groups
permissions
first name
last name
username
You should probably need to check UserAdmin class in depth and see what variables you should override
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2'),
}),
)
form = UserChangeForm
add_form = UserCreationForm
change_password_form = AdminPasswordChangeForm
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
search_fields = ('username', 'first_name', 'last_name', 'email')
ordering = ('username',)
filter_horizontal = ('groups', 'user_permissions',)
Also errors can give you a hint of where something went wrong

Wrong text in selects

I have these model and admin files. It works nice but when I select one activity while adding new Gym Object in the select I see "Activity object" instead of the Activity title.
How can I change these?
# Model
from django.db import models
class Activity(models.Model):
title = models.CharField(max_length=250)
description = models.CharField(max_length=250)
class Gym(models.Model):
name = models.CharField(max_length=250)
pub_date = models.DateTimeField('date published')
where = models.CharField(max_length=250)
description = models.TextField()
timetable = models.TextField()
activities = models.ManyToManyField(Activity, through='GymActivity')
class GymActivity(models.Model):
gym = models.ForeignKey(Gym)
activity = models.ForeignKey(Activity)
# Admin
from django.contrib import admin
from gym.models import Gym, Activity, GymActivity
class GymActivityInline(admin.TabularInline):
model = Gym.activities.through
extra = 6
class GymAdmin(admin.ModelAdmin):
list_display = ['name', 'pub_date']
fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
(None, {'fields': ['where']}),
(None, {'fields': ['description']}),
(None, {'fields': ['timetable']}),
]
inlines = [GymActivityInline]
class ActivityAdmin(admin.ModelAdmin):
list_display = ['title']
admin.site.register(Gym, GymAdmin)
admin.site.register(Activity, ActivityAdmin)
You are missing __unicode__ method on the models
Do this:
class Activity(models.Model):
title = models.CharField(max_length=250)
description = models.CharField(max_length=250)
def __unicode__(self):
return u'%s' % self.title
If you are using Python 3.x, just replace __unicode__ with __str__