I have models.py file as follows.
from django.db import models
class UpdateCreateModelMixin:
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Question(UpdateCreateModelMixin, models.Model):
name = models.CharField(max_length=100)
code = ...
... (Some more field)
How do I display the updated, created fields in the Django model Admin, my admin.py file is
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
list_display = ('name', 'created', 'updated')
list_filter = ('created')
admin.site.register(Question, QuestionAdmin)
For the above admin.py file I am getting this error.
<class 'assignments.admin.QuestionAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'created', which does not refer to a Field.
So, how do I add an inherited fields in the django model Admin and why is the above failing?
class UpdateCreateModelMixin(models.Model):
class Meta:
abstract = True
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Question(UpdateCreateModelMixin):
name = models.CharField(max_length=100)
code = ...
... (Some more field)
Related
models.py
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class BlogModel(models.Model):
id = models.AutoField(primary_key=True)
blog_title = models.CharField(max_length=200)
blog = models.TextField()
status = models.IntegerField(choices=STATUS, default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Blog: {self.blog_title}"
class CommentModel(models.Model):
your_name = models.CharField(max_length=20)
comment_text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Comment by Name: {self.your_name}"
admin.py
from django.contrib import admin
from blog.models import BlogModel,CommentModel
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status','created_at','updated_at')
list_filter = ('status',)
search_fields = ('blog_title', 'content',)
admin.site.register(BlogModel, PostAdmin)
admin.site.register(CommentModel)
I created a simple blog post website with comments and I want to create reports and on the admin panel I have to see how to achieve this.
Like how many posts are created and how many have comments and how many post are draft and published
I checked this module but I don't understand how to implement it https://pypi.org/project/django-reports-admin/
You already have most of this, by using PostAdmin. The list_display already shows you how many posts are published/draft, and the change list has filters for that as well.
To show the comment count, simply add that to list_display:
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status', 'comment_count', 'created_at', 'updated_at')
def comment_count(self, obj):
return obj.commentmodel_set.count()
comment_count.short_description = 'Comment count'
This thus defines a custom method on the PostAdmin, that displays the comment count as a column, and gives it a user-friendly name as column header.
You can expand this with more statistics if you like. The Django admin is highly customizable.
Note: model names should be in CamelCase, so BlogModel and CommentModel should be Blog and Comment respectively.
I want to be able to sort a table column defined using a custom method in the Django admin.
I narrowed down the problem to this simple example in Django:
models.py:
from django.db import models
class MyObject(models.Model):
name = models.CharField(_("name"), max_length=255)
layers = models.URLField(_("Layers"), blank=True, max_length=1024)
choices = models.TextField(
verbose_name=_("Choice values"),
blank=True,
help_text=_("Enter your choice"),
)
class Meta:
verbose_name = _("Object config")
verbose_name_plural = _("Objects config")
def __str__(self): # my custom method
return self.name
and admin.py:
from django import forms
from django.contrib import admin
class MyObjectAdminForm(forms.ModelForm):
"""Form"""
class Meta:
model = models.MyObject
fields = "__all__"
help_texts = {
"layers": "URL for the layers",
}
class MyObjectAdmin(admin.ModelAdmin):
form = MyObjectAdminForm
list_filter = ["name",]
search_fields = ["name",]
# I want the first column (__str__) to be sortable in the admin interface:
list_display = ["__str__", ...] # the ... represent some other DB fields
but for the moment I cannot sort that first column (it is grayed out, I cannot click on its title):
So how could I sort the first column in this admin table as defined by the __str__() method of the MyObject model? (please note that I cannot change the model itself. I'm also brand new to Django, so don't hesitate to detail your answer as if you were speaking to a kid.)
Im using a forigen key to reference another object from my parent object. However when i go to the drop down list created by django admin, i get the object name instead of the field value. how can i add the field value to the form instead?
admin.py
from django.contrib import admin
from .models import Maintenance
from .models import MaintenanceType
from .models import ServiceType
# Register your models here.
class MaintenanceAdmin(admin.ModelAdmin):
list_display = ('Title','Impact','Service','Description','StartTime','EndTime',)
list_editable = ('Title','Impact','Service','Description','StartTime','EndTime',)
admin.site.register(Maintenance, MaintenanceAdmin)
class MaintenanceTypeAdmin(admin.ModelAdmin):
list_display = ('Type',)
list_editable = ('Type',)
admin.site.register(MaintenanceType, MaintenanceTypeAdmin)
class ServiceTypeAdmin(admin.ModelAdmin):
list_display = ('Service','Service',)
list_editable = ('Service','Service',)
admin.site.register(ServiceType, ServiceTypeAdmin)
models.py
from django.db import models
# Create your models here.
class MaintenanceType(models.Model):
Type = models.CharField(max_length=200)
class Meta:
verbose_name = "Planned Maintenance Types"
verbose_name_plural = "Planned Maintenance Types"
class ServiceType(models.Model):
Service = models.CharField(max_length=200)
class Meta:
verbose_name = "Service Types"
verbose_name_plural = "Service Types"
class Maintenance(models.Model):
Title = models.CharField(max_length=200)
Impact = models.ForeignKey(MaintenanceType)
Service = models.ForeignKey(ServiceType)
Description = models.TextField()
StartTime = models.DateTimeField()
EndTime = models.DateTimeField()
class Meta:
verbose_name = "Planned IT Maintenance"
verbose_name_plural = "Planned IT Maintenance"
Implement __str__ in the MaintenanceType model, which should return a string in whatever formatting you wish to appear in the drop down (and anywhere else actually).
It appears that you simply need to return self.Type.
Python 2 only
You can specify what's returned by accessing an object by setting the unicode method to retun what you want it to be.
So I think your MaintenanceType should look like
class MaintenanceType(models.Model):
Type = models.CharField(max_length=200)
class Meta:
verbose_name = "Planned Maintenance Types"
verbose_name_plural = "Planned Maintenance Types"
def __unicode__(self):
return self.Type
I built a simple django application and now have a really confusing error message. I think it's because of Tabularinline, but I use it properly according to this documentation.
models.py
from django.db import models
class Person(models.Model):
company = models.CharField(max_length=120)
name = models.CharField(max_length=120)
birthday = models.DateField(null=True, blank=True)
def __unicode__(self):
return self.name
class Note(models.Model):
person = models.ForeignKey(Person)
datetime = models.DateTimeField()
text = models.TextField()
admin.py
from addressbook.models import Person, Note
from django.contrib import admin
class NoteInline(admin.TabularInline):
model = Note
class PersonAdmin(admin.ModelAdmin):
model = Person
inlines = [NoteInline, ]
admin.site.register(Note, NoteInline)
admin.site.register(Person, PersonAdmin)
But I always get this error message:
<class 'addressbook.admin.NoteInline'>: (admin.E202) 'addressbook.Note' has no ForeignKey to 'addressbook.Note'.
Which I would understand but why should have Note a reference to itself If I am using it from Person?
I don't think you need to separately register the NoteInline admin template. Just register the PersonAdmin template and that should include your NoteInline
I'm getting an error:
AlreadyRegistered at / The model Post is already registered
Why is this happening, and how do I fix it? Here's my models.py :
from django.db import models from
django.contrib import admin
class Post(models.Model):
title = models.CharField(max_length=60)
body = models.TextField()
created = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
class PostAdmin(admin.ModelAdmin):
search_fields = ["title"]
admin.site.register(Post,PostAdmin)
This generally happens when you register you models in models.py file which might be imported into some other modules. The recommended way is to create a separate admin.py file for registering your models.
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=60)
body = models.TextField()
created = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
admin.py
from django.contrib import admin
class PostAdmin(admin.ModelAdmin):
search_fields = ["title"]
admin.site.register(Post,PostAdmin)