I'm using django.contrib.comments for allowing users to comment on a blog.
How is it possible to make the comments display on the Django Admin /admin/comments/comment/ and make them clickable for editing?
[Here should be an image, but since this is my first question and I have no credit, it is not allowed to include images]
The comments can be accessed via /admin/comments/comment/comment_id/ and edited without problems.
Any ideas how to get that solved?
Looking at django.contrib.comments.admin, it should be already visible in your admin panel, provided you added 'django.contrib.comments' to INSTALLED_APPS.
EDIT:
Second look at admin.py from Comments app revelaed that CommentsAdmin.list_display doesn't contain the comment itself. So I would either inherit from that CommentsAdmin, override list_display and then unregister and re-register Comment with MyNewCommentsAdmin - or I would just monkey-patch CommentsAdmin. Whichever works.
Thank you Tomasz,
The problem was 'content_type' in list_display, which resulted in nothing at all displayed. Removing it from MyCommentsAdmin resolved the problem:
app/admin.py:
class MyCommentsAdmin(admin.ModelAdmin):
fieldsets = (
(_('Content'),
{'fields': ('user', 'user_name', 'user_email', 'user_url', 'comment')}
),
(_('Metadata'),
{'fields': ('submit_date', 'ip_address', 'is_public', 'is_removed')}
),
)
list_display = ('name', 'ip_address', 'submit_date', 'is_public', 'is_removed')
list_filter = ('submit_date', 'site', 'is_public', 'is_removed')
date_hierarchy = 'submit_date'
ordering = ('-submit_date',)
raw_id_fields = ('user',)
search_fields = ('comment', 'user__username', 'user_name', 'user_email', 'user_url', 'ip_address')
admin.site.unregister(Comment)
admin.site.register(Comment, MyCommentsAdmin)
urls.py:
from django.contrib import admin
admin.autodiscover()
import app.admin
add to answer Meilo:
if you use standard comment's framework (like: #in url.py
url(r'^comments/', include('django.contrib.comments.urls')),
you wish overwrite behavior comments model, you need import
#apps.admin.py
from django.contrib.comments.models import Comment
Related
Was just following the tutorials from Django documentation.
In Writing your first Django app, part 7, the tutorial was adding the Choice section when a user is adding a Question.
In the documentation, the code seems to work fine, but in my system, for some reason it isn't working. Please tell me where I got it wrong.
code:
from django.contrib import admin
from .models import Choice, Question
# Register your models here.
class ChoiceInline(admin.TabularInline):
model: Choice
extra: 3
class QuestionAdmin(admin.ModelAdmin):
# fields = ['pub_date', 'question_text']
fieldsets = [
(None, {'fields': ['question_text']}),
('Date Information', {'fields': ['pub_date'],
'classes':['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Question, QuestionAdmin)
Error:
<class 'polls.admin.QuestionAdmin'>: (admin.E105) 'polls.admin.ChoiceInline' must have a 'model' attribute.
When using django mailer (https://github.com/pinax/django-mailer) I realized that the default tables added to the admin area (such as Message logs and Messages) did not add the message_log field which indeed is available if one looks at the tables that are added.
Since the error message is very valuable to me I wanted to add it, and simply added the "log_message" to the app's MessageLogAdmin like this:
class MessageLogAdmin(MessageAdminMixin, admin.ModelAdmin):
list_display = ["id", show_to, "subject", "message_id", "when_attempted", "result", "log_message"]
list_filter = ["result"]
date_hierarchy = "when_attempted"
readonly_fields = ['plain_text_body', 'message_id']
search_fields = ['message_id']
However, is there really no other way to customize the admin area for django-mailer other than modifying the source code? E.g through settings.py
No you can't do that via settings.py
If I understand correctly, you don't want to fork the app just to edit admin.py, but rather keep it in the requirements.txt file. In that case you could do something like:
class MyOwnMessageLogAdmin(MessageAdminMixin, admin.ModelAdmin):
list_display = ["id", show_to, "subject", "message_id", "when_attempted", "result", "log_message"]
list_filter = ["result"]
date_hierarchy = "when_attempted"
readonly_fields = ['plain_text_body', 'message_id']
search_fields = ['message_id']
admin.site.unregister(MessageLog)
admin.site.register(MessageLog, MyOwnMessageLogAdmin)
I have following model
from django.db import models
class Ipaddress(models.Model):
ipaddress=models.CharField(max_length=20)
slug = models.SlugField(unique=True)
machinename=models.CharField(max_length=500)
user=models.CharField(max_length=200)
department= models.ForeignKey('Department',on_delete=models.CASCADE,default='Empty')
location= models.ForeignKey('Location', on_delete=models.CASCADE)
updated = models.DateField("Date Updated",null=True)
note =models.TextField()
def __str__(self):
return self.ipaddress[:50]
In the admin page:
from django.contrib import admin
from pages.models import Post, Device, DeviceType, DeviceModel, Ipaddress, DeviceGroup, Location,Department,Comment
from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter
class IpaddressAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('ipaddress',)}
search_fields = ['ipaddress', ]
list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',)
list_filter = (
('user', DropdownFilter),
('department', RelatedDropdownFilter),
('location', RelatedDropdownFilter),
)
When I try to add a device it shows following page:
The location of the list could be a few thousand racks. So, i need to type the rack instead of scrolling 1000 of records. Any idea how i can do that.
Until someone shares a complex solution i suggest you add your ForeignKey Location to your search_fields instead like:
search_fields = ['foreign_key__related_fieldname']
So if your "location names" are defined with the field 'title' in your Location model you could do:
from django.contrib import admin
from .models import Ipaddress
class IpaddressAdmin(admin.ModelAdmin):
search_fields = ['ipaddress', 'location__title']
admin.site.register(Ipaddress, IpaddressAdmin)
Note: stripped it down to the essential in this example that assumes this is in app/admin.py and that the Ipadress model is in app/models.py
This is really convenient since django admin breaks down multiple search words (seperated by spaces) so you can search for "ip location" like:
127.0.0.1 Sweden
And it would search both your 'ipadress' field and your ForeignKey 'Location'.
Pros:
Fast! No need to reload the view twice if you need to search after applying filter!
Simple
Cons:
Possibly slower querying if one adds many foreign keys for search_fields or has a huge amount of objects in the foreign key model.
Django 2.1 docs: ModelAdmin.search_fields
I have an image field in my models.py...
qr_image = models.ImageField(
upload_to="public/uploads/",
height_field="qr_image_height",
width_field="qr_image_width",
null=True,
blank=True,
editable=False
)
When it's editable=False I get a nasty error when trying show it. I don't want the field editable, however I do want the image to show in admin 'edit' page i.e. fieldsets
I'm new to Django, can someone tell me if this is possible and point me in the right direction here?
thank you.
If you have a ModelAdmin like this:
class MyModelAdmin(admin.ModelAdmin):
fieldsets = [
('Fieldset', {'fields': ['model_field', 'another_field', 'readonly_field']}),
]
where readonly_field has editable=False or if it is a DateTimeField with auto_now_add=True then visiting the admin page for your model will result in a field not found error.
To include a readonly field in your fieldsets, include readonly_fields like this:
class MyModelAdmin(admin.ModelAdmin):
fieldsets = [
('Fieldset', {'fields': ['model_field', 'another_field', 'readonly_field']}),
]
readonly_fields = ('readonly_field',)
An easy way to accomplish this is to make the field read-only in the ModelAdmin: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields
I have little doubt that this will be a really stupid question. But I really can't figure it out so I'll ask it anyway.
In /svsite/src/svsite/member/models/svuser.py (a little unusual location, see this question Place Django admin forms in different files).
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin, UserChangeForm as DjangoUserChangeForm
from svsite.member.models.svuser import svUser
class UserChangeForm(DjangoUserChangeForm):
class Meta:
pass
class svUserAdmin(UserAdmin):
form = UserChangeForm
readonly_fields = ('date_joined', 'last_login', 'last_update', )
fieldsets = \
(
(
'Login',
{
'classes': ('collapse', ),
'fields':
(
'username',
'password',
'is_active',
'email_verified',
'awaiting_user_confirmation',
),
}
),
(
'Personal info',
{
'fields':
(
'first_name',
'middle_name',
'last_name',
),
}
),
)
[...]
In the model I have at /svsite/src/svsite/member/admin/svuser.py:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User, UserManager
class svUser(User):
email_verified = models.BooleanField(default = False)
awaiting_user_confirmation = models.BooleanField(
_('approved by board'), default = False, help_text=_('This user\'s identity was confirmed by the board or another authority.'))
[...]
The error I get:
'svUserAdmin.fieldsets[0][1]['fields']' refers to field 'password' that is missing from the form.
If I comment password, the error moves to the next field. Independent if it's a default user model field or one I added in the svUser inherited from user. Very surprisingly (to me), username seems to be the only field that works, no problems on that one.
I found this question Django ModelAdmin - fieldsets ... field 'date' missing from the form and even though the fields are not auto_now, I added them to readonly_fields and that made the error go away. Obviously though, making all fields read-only is not an option.
It's probably something stupid not really related to code but I really can't find it, seems to me it really should be working. Any help is greatly appreciated!
The problem appears to be because you're using a ModelForm for a model that you are not editing.
I tried a simliar situation and got a similar error pattern.
class UserChangeForm(DjangoUserChangeForm):
class Meta:
model = svUser # update the model - default form points to User