I'm using Django 1.6 as backend, what I want to do is to let users write their comments while watching the video. I wrote the field
datetime = models.DateTimeField(auto_now_add=True)
in the model.py, but in the Django back-end, I didn't see this column, how can I let it show in my admin? Thanks!
Just add readonly_fields option to you admin.py:
class CommentAdmin(admin.ModelAdmin):
readonly_fields = ('datetime',)
If you have fields option defined in you admin class, you'll also have to add datetime to the fields option:
class CommentAdmin(admin.ModelAdmin):
# display datetime in the changelist
list_display = ('id', 'title', 'datetime')
# display datetime when you edit comments
readonly_fields = ('datetime',)
# optional, use only if you need custom ordering of the fields
fields = ('title', 'body', 'datetime')
admin.site.register(Comment, CommentAdmin)
For more info, please see:
https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields
You can set a field of a model to be shown in admin by adding it to the ModelAdmin (in admin.py of the model's app):
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
list_display = ('datetime',)
admin.site.register(MyModel, MyModelAdmin)
And to set the short description that is displayed next to the field, you need to set verbose_name of the field, like the following (in models.py):
class MyModel(models.Model):
datetime = models.DateTimeField(auto_now_add=True, verbose_name="Uploaded at")
Note: You don't need to set readonly_fields since DateTimeField with auto_now_add=True arg will be read-only by default.
Related
I have 2 models involved.
class Purchase():
......
class PremiumBill():
purchase = models.ForeignKey
paid_at = models.DateTimeField
in my admin.py in the PurchaseAdmin
list_filter = ("premiumbill__paid_at",)
it gives me this error
Filtering by premiumbill__paid_at__gte not allowed
I have a Comment table on Django Admin:
models.py
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(Listing, on_delete=models.CASCADE)
comment = models.TextField(max_length=250)
datetime = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.item}"
admin.py
class CommentInline(admin.TabularInline):
model = Comment
class ItemAdmin(admin.ModelAdmin):
inlines = [
CommentInline,
]
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('item','user','comment','datetime',)
list_filter = ('item',)
And I want to edit this table with the same values item that will display with a single row, and then after clicked on it will display another table contain user comment and datetime .
Thanks so much for any advice to me !!!
If item is a foreign key to one of your other models, you should be able to use an InlineModelAdmin object to create a tabular inline view of the user/comment/datetime using the item's admin view.
See
https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects for reference.
In your case you may end up with something like:
class CommentInline(admin.TabularInline):
model = Comment
fields = ('user', 'comment', 'datetime')
class ItemAdmin(admin.ModelAdmin):
inlines = [
CommentInline,
]
If item is a models.CharField though I don't think you can do it with the Django Admin as provided by Django.
I have a model
class College(models.Model):
is_published = models.NullBooleanField(default=False)
name = models.CharField(max_length=255)
I registered the model in admin.py
#admin.register(College)
class CollegeAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
Now I want to have a button on the admin panel, on pressing which I can change the is_published field of all the objects in the model to True.
I have no idea how should I proceed. Any working code snippet will be appreciated.
A custom admin action is the perfect tool for this job.
For example (copied almost word for word from the documentation):
def publish(modeladmin, request, queryset):
queryset.update(is_published=True)
publish.short_description = "Mark selected stories as published"
#admin.register(College)
class CollegeAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
actions = [publish]
I have a Django project hosted on heroku
I added a new slug field to model
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.name
migrated it using south on heroku. Checked the heroku postgresDB as well for added field. All fine.
Opened Admin. No slug field showing...
added slug to fields[] in admin.py. Still not showing. Here is admin.py
from django.contrib import admin
from models import Category
class CategoryAdmin(admin.ModelAdmin):
fields = ('name', 'slug')
admin.site.register(Category, CategoryAdmin).
I even did a heroku restart... No change.
What can be done to show it ?
Try to use list_display like following:
from django.contrib import admin
from models import Category
class CategoryAdmin(admin.ModelAdmin):
fields = ('name', 'slug')
#list of fields to display in django admin
list_display = ['id', 'name', 'slug']
#if you want django admin to show the search bar, just add this line
search_fields = ['name', 'slug']
#to define model data list ordering
ordering = ('id','name')
admin.site.register(Category, CategoryAdmin).
Just in case someone ever faces this scenario
My admin classes were inheriting from UserAdmin, when they should have been inheriting from admin.ModelAdmin.
I had to change
class Model1(UserAdmin):
....
to
class Model1(admin.ModelAdmin):
....
I see the solution in here Django Website: https://docs.djangoproject.com/en/3.2/ref/models/fields/#editable, use fields's editable property.
editable
Field.editable
If False, the field will not be displayed in
the admin or any other ModelForm. They are also skipped during model
validation. Default is True.
I have posted a png image before, but I don't know how to display it.
In change list view in django admin interface, is it possible to mark some fields/rows red in if they achieve a expression?
For example, if there is a model Group with members and capacity, how can I visualize when they are full or crowded?
For modifying how and what is displayed in change list view, one can use list_display option of ModelAdmin.
Mind you, columns given in list_display that are not real database fields can not be used for sorting, so one needs to give Django admin a hint about which database field to actually use for sorting.
One does this by setting admin_order_field attribute to the callable used to wrap some value in HTML for example.
Example from Django docs for colorful fields:
class Person(models.Model):
first_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
def colored_first_name(self):
return '<span style="color: #%s;">%s</span>' % (
self.color_code, self.first_name)
colored_first_name.allow_tags = True
colored_first_name.admin_order_field = 'first_name'
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'colored_first_name')
I hope some of this helps.
This is an old question but I'll add an example from docs for Django 1.10 because allow_tags attribute used in the accepted answer is deprecated since Django 1.9 and it is recommended to use format_html instead:
from django.db import models
from django.contrib import admin
from django.utils.html import format_html
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
def colored_name(self):
return format_html(
'<span style="color: #{};">{} {}</span>',
self.color_code,
self.first_name,
self.last_name,
)
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'colored_name')
In addition you can use
colored_first_name.short_description = 'first name'
For a nice column title