SystemCheckError (slug in django) - python

I got this error (what is wrong here? I can't find the root cause of this. I tried to search for this answer but it didn't applied to this case.):
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'rango.admin.CategoryAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slugs', which is not an attribute of 'rango.Category'.
My admin.py
from django.contrib import admin
from .models import Category, Page
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slugs':('name',)}
class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'url')
admin.site.register(Category, CategoryAdmin)
admin.site.register(Page, PageAdmin)
My models.py
from django.db import models
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self):
return self.title

You have field named slug in your model, but you are using slugs in admin. You need to change it to slug also:
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('name',)}

Related

How to hide specific field by User Group on a django admin

i want to hide a specific line of my Django Admin Model by permission or Group
My models.py
class Post(models.Model):
title = models.CharField(max_length=128)
slug = AutoSlugField(populate_from='title')
category = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='actus')
is_verified = models.BooleanField(default=False)
content = RichTextField(blank=True, null=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
thumbnail = models.ImageField(upload_to='media/thumbs', blank=True, null=True, default="media/thumbs/default.jpg")
date = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("post", kwargs={"slug": self.slug, "category": self.category})
My Model admin
from django.contrib import admin
from django.db import models
from django.db.migrations.graph import Node
from django.utils.regex_helper import Group
from .....models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'date', 'is_verified')
list_filter = ('date', 'author', 'is_verified')
admin.site.site_header = 'Staff Dashboard'
admin.site.register(Post, PostAdmin)
My django admin page
Django admin page
If someone has an idea
You can define two ModelForms: one with the is_verified option, and one without, so:
# app_name/forms.py
from django import forms
from app_name.models import Post
class NormalUserPostForm(forms.ModelForm):
class Meta:
model = Post
exclude = ['is_verified']
class AdminUserPostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
then we can override the get_form method of the ModelAdmin:
# app_name/admin.py
from app_name.forms import NormalUserPostForm, AdminUserPostForm
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'date', 'is_verified')
list_filter = ('date', 'author', 'is_verified')
form = NormalUserPostForm
def get_form(self, request, obj=None, **kwargs):
if request.user.is_superuser:
kwargs['form'] = AdminUserPostForm
return super().get_form(request, obj, **kwargs)
admin.site.site_header = 'Staff Dashboard'
admin.site.register(Post, PostAdmin)
You can change the condition to request.user.has_perm('some_permission') to check for a certain permission instead.

How to show in Django Admin the list of Activities a user has made

I am trying to get the most out of my Django Blog project and wanted to know how to show in the admin the activities that a user has made like making comments or giving likes to posts.
I need some hints and guidance on how to add this information in the admin.py
Here is the models.py in Blog App
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
content = RichTextUploadingField(null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
date_posted = models.DateTimeField(default=timezone.now)
slug = models.SlugField(blank=True, null=True, max_length=120)
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post-detail', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'Blog Posts'
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField(max_length=300)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.post}-{self.user}-Comment No.{self.pk}"
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike')
)
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
value = models.CharField(choices=LIKE_CHOICES, max_length=8)
created = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.post}-{self.user}-{self.value}"
Here is the models.py in Users App
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
This is what I have tried in the models.py in Users app but didn't work
# Get the no. of posts
def get_posts_no(self):
return self.author.all().count()
# Get the no. of likes
def get_likes_given(self):
likes= set.like_set.all()
total_liked=0
for item in likes:
if item.value=='Like':
total_liked+=1
return total_liked
"... to add this information in the admin.py" → do you mean to say that you would like to show an additional column in the Django admin site with said information? If so, then the answer is:
In your admin.py, extend the PostAdmin class with a custom queryset and add comments_count and likes_count to list_display = (...):
from django.contrib import admin
from django.db.models import Count
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'date_posted', 'comments_count', 'likes_count')
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(
_comments_count=Count('comment_set', distinct=True),
_likes_count=Count('like_set', distinct=True)
)
return queryset
def comments_count(self, obj):
if hasattr(obj, '_comments_count'):
return obj._comments_count
return None
def likes_count(self, obj):
if hasattr(obj, '_likes_count'):
return obj._likes_count
return None
comments_count.admin_order_field = '_comments_count'
likes_count.admin_order_field = '_likes_count'
admin.site.register(Post, PostAdmin)

Am having troubles with django-parler 2.0.1 after i had applied migration to translations, it won't show Products fields in admin site

this is my setting for translations in the models.py file, django-parler 2.0.1 won't show fields for Products in the admin site after I had synch migrations. I am currently using Django 3.0.3.
from django.db import models
from django.urls import reverse
from parler.models import TranslatableModel, TranslatedFields
class Category(TranslatableModel):
translations = TranslatedFields(
name = models.CharField(max_length=200,
db_index=True),
slug = models.SlugField(max_length=200,
db_index=True,
unique=True)
)
class Meta:
# ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category',
args=[self.slug])
class Product(TranslatableModel):
translations = TranslatedFields(
name = models.CharField(max_length=200, db_index=True),
slug = models.SlugField(max_length=200, db_index=True),
description = models.TextField(blank=True)
)
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
#class Meta:
# ordering = ('name',)
# index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
I have registered the model in the admin.py file but it won't show the fields for product description and price all I get is the translated tab.
from django.contrib import admin
from .models import Category, Product
from parler.admin import TranslatableAdmin
#admin.register(Category)
class CategoryAdmin(TranslatableAdmin):
list_display = ['name', 'slug']
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('name',)}
#admin.register(Product)
class ProductAdmin(TranslatableAdmin):
list_display = ['name', 'slug', 'price',
'available', 'created', 'updated']
list_filter = ['available', 'created', 'updated']
list_editable = ['price', 'available']
def get_prepopulated_fields(self, request, obj=None):
return {'slug': ('name',)}
I wonder what am doing wrong that I am getting this and I wonder if there's a better way to make translate configurations with Django-parler 2.0.1. any suggestions is welcomed!!
Apparently, I was able to fix the problem by first deleting all migrations and I also had to trash my database and switch to PostgreSQL and after that, I reapplied migrations and it worked. All fields are now visible in the admin site now yippee! but be mindful to make a backup of your database because everything will be deleted..

Django Admin: Register multiple admin classes to the same model

Is it possible to register multiple admin classes to the same model? I want to have both PostAdmin and MyPostAdmin register to the Post model. Right now I'm trying to use a proxy model with MyPost, but it's giving me two different models in the admin panel with their separate functionality.
admin.py:
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
class MyPostAdmin(SummernoteModelAdmin):
summernote_fields = ('text', )
admin.site.register(Post, PostAdmin)
admin.site.register(MyPost, MyPostAdmin)
models.py:
class Post(models.Model):
title = models.CharField(max_length=250)
category = models.IntegerField(choices=category_choices, default=0)
description = models.TextField(max_length=250, blank=True, null=True)
text = models.TextField()
thumbnail = models.ImageField(upload_to=settings.MEDIA_URL)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
slug = models.SlugField(unique=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def __str__(self):
return self.title
class MyPost(Post):
class Meta:
proxy = True
Turns out I didn't need to make a proxy model. I fixed the issue by adding the prepopulated_fields variable to the MyPostAdmin class
In this specific case of SummernoteModelAdmin, you can use multiple inhertance for creating a single admin class instead of using PRoxy Models:
class MyPostAdmin(SummernoteModelAdmin, admin.ModelAdmin):
summernote_fields = ('text', )
prepopulated_fields = {'slug':('title',)}
admin.site.register(Post, PostAdmin)

Error with ordering Django 1.9 models how to fix this?

Output from CMD:
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS: posts.Comments: (models.E015) 'ordering' refers to the
non-existent field 'timestamp'. posts.Comments: (models.E015)
'ordering' refers to the non-existent field 'updated'.
System check identified 2 issues (0 silenced).
Current code:
from __future__ import unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.text import slugify
class PostManager(models.Manager):
def active(self, *args, **kwargs):
return super(PostManager, self).filter(draf=False).filter(publish__lte=timezone.now())
def upload_location(instance, filename):
return "%s/%s" %(instance.id, filename)
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=70)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
content = models.TextField(max_length=220)
draf = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
class Comments(models.Model):
class Meta:
db_table = 'comments'
comments_text = models.CharField(max_length=120)
comments_posts = models.ForeignKey(Post)
objects = PostManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
#return "/posts/%s/" %(self.id)
class Meta:
ordering = ["-timestamp", "-updated"]
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
You are ordering on the fields timestamp and updated from the Comments model which do not exists, and not on the related Post model. Just as your error said:
'ordering' refers to the non-existent field 'timestamp'.
'ordering' refers to the non-existent field 'updated'.
You can filter on related model-fields by using the double underscore __:
relationfield__fieldname.
class Meta:
ordering = ["-comments_posts__timestamp", "-comments_post__updated"]
Model Comment doesn't have following fields
class Meta:
ordering = ["-timestamp", "-updated"]

Categories