Django widget override in admin not working - django

I've been trying to change the widget used in the admin but can't seem to get it to work - there is presumably something I'm not doing quite right after looking at the docs. I'm get a models is not defined error but defining models or changing models.ManyToManyField to use the actual Product.ManyToManyField doesn't seem to work either?
#admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ('supplier', 'name', 'last_updated')
# model = Product
inlines = [ProductPricesInline,]
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}

you forgot to import models?
from django.db import models
# ...
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}

Related

Django Admin is not showing list and filter options

When I get yo the Admin site, the models page is not showing my list_display or filter options.
I can get in a model and change database info, that seems to work ok. It just seems not to recognizes my setup.
It used to work just fine, I donĀ“t know exactly when in my app update this started happening.
from django.contrib import admin
from .models import ProductosBase, Marcas, Categorias_Producto
admin.site.register(ProductosBase)
class ProductosBaseAdmin(admin.ModelAdmin):
list_display = ('marca', "categoria_producto", "producto", "color", "foto_1")
list_filter = ('marca', "categoria_producto", "producto")
fields = (("codigo_kinemed", 'marca'), ("categoria_producto", "producto"), ("color", "packaging"), ("ancho", "largo"), ("units_inner", "inner_master", "tier"), "descripcion", "foto_1", "foto_2", "video_link")
def __unicode__(self):
return self.name
admin.site.register(Marcas)
class Marcas(admin.ModelAdmin):
list_display = 'marcas'
fields = ['marcas']
admin.site.register(Categorias_Producto)
class Categorias_Producto(admin.ModelAdmin):
list_display = 'Categorias_Producto'
`enter code here`fields = ['Categorias_Producto']
You need to include the ModelAdmin subclass with the register call.
class ProductosBaseAdmin(admin.ModelAdmin):
list_display = ('marca', "categoria_producto", "producto", "color", "foto_1")
list_filter = ('marca', "categoria_producto", "producto")
fields = (("codigo_kinemed", 'marca'), ("categoria_producto", "producto"), ("color", "packaging"), ("ancho", "largo"), ("units_inner", "inner_master", "tier"), "descripcion", "foto_1", "foto_2", "video_link")
def __unicode__(self):
return self.name
admin.site.register(ProductosBase, ProductosBaseAdmin)
class MarcasAdmin(admin.ModelAdmin):
list_display = 'marcas'
fields = ['marcas']
admin.site.register(Marcas, MarcasAdmin)

admin.py: "model = Thing" ,what does this code mean?if without it what gonna happen?

every one,,I am reading a Django practice book,,I saw a code "model = Thing" in admin.py,,,however, when I remove "model = Thing",,,the web program still can run,the admin site looks no difference??,what does this code mean?if without it what gonna happen? my models.py class is Thing
admin.py
from django.contrib import admin
from collection.models import Thing
class ThingAdmin(admin.ModelAdmin):
model = Thing #if I remove this code, the program still can run,,why need this code
list_display = ('name', 'description',)
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Thing, ThingAdmin)
modles.py
from django.db import models
class Thing(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(unique=True)
Setting a model attribute on the ModelAdmin class will have no effect. You can safely remove that line from your code.
In the Django admin, you specify the model when you call admin.site.register(), or by using the register decorator. This allows you to use the same model admin class for more than one model.
admin.site.register(Thing, ThingAdmin)
admin.site.register(OtherThing, ThingAdmin)
As Jon pointed out in the comments, you do need to specify the model for InlineModelAdmin objects.

Django-Taggit in Edit Form

This is a Model Class
class ModelName(models.Model):
(...)
pasta = TaggableManager(verbose_name=u'Pasta')
and a form template (normal :P )
{{form.as_p}}
I'd like to leave everything very clean and usefull.
But result is a list of TaggedItem Object :( :
[<TaggedItem: id: 2 tagged with general >, <TaggedItem: id: 3 tagged with outer >]
Instead of something like
general, outer
How do it fashionably in Django?
Give a look at the code in: https://github.com/alex/django-taggit/blob/master/taggit/forms.py. You will find the widget used to render the tags. You can use it to render them correctly.
Example:
models.py
from django.db import models
from taggit.managers import TaggableManager
class Example(models.Model):
name = models.CharField(max_length=20)
tags = TaggableManager()
forms.py
.models import Example
from django import forms
from taggit.forms import TagWidget
class ExampleForm(forms.ModelForm):
class Meta:
model = Example
fields = ('name', 'tags',)
widgets = {
'tags': TagWidget(),
}
I'd recommend you to check this answer too.
django - django-taggit form
I would use django-taggit-autosuggest as it offers better UI to the user.

Django models and admin panel

Hi guys I have this model
class Class1(models.Model):
....
ctime = models.FloatField() # I am storing date in timestamp here
....
Is it possible to display ctime field in admin panel not as float but as time field?
Check Django documentation. You can override default widgets for model fields -
from django.db import models
from django.contrib import admin
# Import our custom widget and our model from where they're defined
from myapp.widgets import RichTextEditorWidget
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': RichTextEditorWidget},
}
Or, for a single model, as described in this answer -
class StopAdminForm(forms.ModelForm):
class Meta:
model = Stop
widgets = {
'approve_ts': ApproveStopWidget(),
}
class StopAdmin(admin.ModelAdmin):
form = StopAdminForm
Check other answers in that question too.a

Django: Admin: changing the widget of the field in Admin

I have a model with a boolean value like that:
class TagCat(models.Model):
by_admin = models.BooleanField(default=True)
This appears as a checkbox in admin.
How could I use this as a radio button in admin?
Also, how do I make it be always with a certain selected value in admin?
Also, I want the default value to be the opposite, when a non-admin user adds a TagCat. This field should be hidden from him.
Can someone tell me how to do this? Django documentation doesn't seem to go in such details.
UPDATE 1: Code that gets me done with 1) (don't forget tot pass CHOICES to the BooleanField in the model)
from main.models import TagCat
from django.contrib import admin
from django import forms
class MyTagCatAdminForm(forms.ModelForm):
class Meta:
model = TagCat
widgets = {
'by_admin': forms.RadioSelect
}
fields = '__all__' # required for Django 3.x
class TagCatAdmin(admin.ModelAdmin):
form = MyTagCatAdminForm
admin.site.register(TagCat, TagCatAdmin)
The radio buttons appear ugly and displaced, but at least, they work
I solved with following info in MyModel.py:
BYADMIN_CHOICES = (
(1, "Yes"),
(0, "No"),
)
class TagCat(models.Model):
by_admin = models.BooleanField(choices=BYADMIN_CHOICES,default=1)
There is another way to do this that is, IMO much easier if you want every field of the same type to have the same widget. This is done by specifying a formfield_overrides to the ModelAdmin. For example:
from django.forms.widgets import Textarea
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': Textarea},
}
More in the docs: https://docs.djangoproject.com/en/1.4/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides
Here is a more dynamic extension of mgPePe's response:
class MyAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyAdminForm, self).__init__(*args, **kwargs)
self.fields['by_admin'].label = 'My new label'
self.fields['by_admin'].widget = forms.RadioSelect()
class Meta:
model = TagCat
class MyAdmin(admin.ModelAdmin):
fields = ['name', 'by_admin']
form = MyAdminForm
This way you get full control over the fields.