class DocumentForm(forms.ModelForm):
model = Document
starred_by = forms.ModelMultipleChoiceField(queryset=User.objects.all())
class Meta:
widgets = {
'created_by': AutocompleteSelect(
Document._meta.get_field('created_by').remote_field,
admin.site,
attrs={'data-dropdown-auto-width': 'true'}
),
'organisation': AutocompleteSelect(
Document._meta.get_field('created_by').remote_field,
admin.site,
attrs={'data-dropdown-auto-width': 'true'}
),
'starred_by':AutocompleteSelectMultiple(
Document._meta.get_field('starred_by').remote_field,
admin.site,
attrs={'data-dropdown-auto-width': 'true'}
)
}
Update:
I have read a bit about the select2 library but I am having trouble understanding how do I integrate it with Django-admin my requirements mostly are searchable select dropdown for foreign keys and multi-select dropdowns for many-to-many fields but these fields I want in the Django admin panel in my apps, any help will be appreciated, thanks in advance
This is how I solved it , I used Django's native search fields which uses Sleect2 under the hood
class OrganisationAdmin(admin.ModelAdmin):
list_display = ('name','address')
autocomplete_fields = ['products']
search_fields = ['name__iexact']
# autocomplete_fields = ['']
class ProductAdmin(admin.ModelAdmin):
search_fields = ['name']
Related
I want to override the basic view in the Article snippet selector, which does not display the checkbox correctly.
class ArticleChooserMixin(ModelChooserMixin):
def get_edit_item_url(self, item):
# for Wagtail 4.x
return reverse(
"wagtailsnippets_app_name_article:edit", args=(quote(item.pk),)
)
class ArticleChooserViewSet(ModelChooserViewSet):
icon = "user"
model = Article
page_title = _("Choose a article")
per_page = 10
order_by = "title"
fields = ["title", "body", "url", "categories", "countries"]
chooser_mixin_class = ArticleChooserMixin
piece of code from the Article model
from dal import autocomplete
...
#register_snippet
class Article(
DraftStateMixin,
RevisionMixin,
index.Indexed,
ClusterableModel,
Orderable,
SourceDataMixin,
):
...
categories = ParentalManyToManyField("app_name.ArticleCategory", blank=True)
countries = ParentalManyToManyField("app_name.Country", blank=True)
...
FieldPanel("categories", widget=autocomplete.ModelSelect2Multiple())
FieldPanel("countries", widget=autocomplete.ModelSelect2Multiple()),
...
Similar problem: https://github.com/wagtail/wagtail-generic-chooser/issues/65
View from the snippet creation how I want it to look and form elements that display the currently selected item
current problem
As per the wagtail-generic-chooser docs - The creation form presented within the chooser is a plain Django ModelForm, which does not make use of the model's panel definition. If you pass a fields attribute on the ViewSet class, it will construct a ModelForm with all of those fields at their default settings. To override this, you can define your own ModelForm class and pass that as form_class:
from django import forms
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ["title", "body", "url", "categories", "countries"]
widgets = {
"categories": autocomplete.ModelSelect2Multiple(),
"countries": autocomplete.ModelSelect2Multiple(),
}
class ArticleChooserViewSet(ModelChooserViewSet):
# ...
form_class = ArticleForm
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)
Unfortunately, I'm still using django 1.4 and the verbose_name doesn't work for foreign keys.
It is there a way to change the label of a foreign key. For now, it is not working:
class ProductVariant(models.Model):
product = models.ForeignKey(TestProduct, verbose_name='test product', on_delete=models.PROTECT)
ProductVariant
class ProductVariantForm(forms.ModelForm):
product = forms.ModelChoiceField(queryset=TestProduct.objects.order_by("product__article_code"))
test_software = forms.ModelChoiceField(queryset=TestSoftware.objects.order_by("name"))
class Meta:
model = ProductVariant
class ProductVariantAdmin(admin.ModelAdmin):
fields=["product", "test_software", "test_variables", "name", "description"]
list_display = ("name", "product_name", "test_software_name", "test_variables", "description")
search_fields = ["name"]
form = ProductVariantForm
I hope you can help me.
Thanks in advance!
verbose_name should work with Django 1.4 according to the 1.4 docs.
I think because you're overriding the field in the form it's not using the verbose name for the label. What you could do is set the label on the ModelChoiceField.
class ProductVariantForm(forms.ModelForm):
product = forms.ModelChoiceField(label="Test Product", queryset=TestProduct.objects.order_by("product__article_code"))
test_software = forms.ModelChoiceField(queryset=TestSoftware.objects.order_by("name"))
class Meta:
model = ProductVariant
I'm not quite sure how to use the model's verbose name on the field though, so you might have to define it twice.
I have a model with auto_now, and auto_now_add set for Update and Create fields:
class HotelProfiles(models.Model):
fe_result_id = models.AutoField(primary_key=True)
fe_created_date = models.DateTimeField(verbose_name='Created',
blank=True,
auto_now_add=True)
fe_updated_date = models.DateTimeField(verbose_name='Updated',
blank=True,
auto_now=True)
In the Admin it displays both fields but leaves them uneditable. They
don't seem to be passed to my form to be rendered. I don't want them
to be editable, but I would like to display at the top of my form.
How can I do this?
This is in my HotelProfilesAdmin class:
readonly_fields = ('fe_result_id', 'fe_created_date', 'fe_updated_date', 'fe_owner_uid')
#date_hierarchy = 'lto_end_date'
fieldsets = (
("Internal Use Only", {
'classes': ('collapse',),
'fields': ('fe_result_id', 'fe_created_date', 'fe_owner_uid', 'fe_updated_date', 'fe_result_status')
}),
Make the fields you want readonly
explicitly override what fields are available in this admin form (readonly fields will be present but readonly)
Example:
from django.contrib import admin
class HotelProfilesAdmin(admin.ModelAdmin) :
# Keep the fields readonly
readonly_fields = ['fe_created_date','fe_updated_date']
# The fields in the order you want them
fieldsets = (
(None, {
'fields': ('fe_created_date', 'fe_updated_date', ...other fields)
}),
)
# Add your new adminform to the site
admin.site.register(HotelProfiles, HotelProfilesAdmin)
For the benefit of others, I figured out a way to do this. I'm new to Django, so if there is a better way, I'd be interested in hearing it. The view code is below. I wasn't sure if Django was not returning the fields from the query, and I found out that it was. So, something in the renderering of the form that I don't understand removed those fields so they couldn't be rendered. So, I copied them to a dict called read_only before rendering and passed it along.
try:
hotel_profile = HotelProfiles.objects.get(pk=hotel_id)
read_only["created_on"] = hotel_profile.fe_created_date
read_only["updated_on"] = hotel_profile.fe_updated_date
f = HotelProfileForm(instance=hotel_profile)
#f.save()
except:
f = HotelProfileForm()
print 'rendering blank form'
return render_to_response('hotels/hotelprofile_form.html', {'f' : f, 'read_only': read_only}, context_instance=RequestContext(request))
I can I add fields to a model formset? It seems you can add fields if you user normal formset but not with model formsets (at least it's not the same way). I don't think I should use inline formset either ..?
I want to let users edit their photoalbum (django-photologue). So far I've manage to do this:
PhotoFormSet = modelformset_factory(Photo,
exclude=(
'effect',
'caption',
'title_slug',
'crop_from',
'is_public',
'slug',
'tags'
))
context['gallery_form'] = PhotoFormSet(queryset=self.object.gallery.photos.all())
The problem is that I have to add a checkbox for each photo saying "Delete this photo" and a radio select saying "Set this to album cover".
Thanks in advance!
You can add fields. Just define a form in the normal way, then tell modelformset_factory to use that as the basis for the formset:
MyPhotoForm(forms.ModelForm):
delete_box = forms.BooleanField()
class Meta:
model = Photo
exclude=('effect',
'caption',
'title_slug',
'crop_from',
'is_public',
'slug',
'tags'
))
PhotoFormSet = modelformset_factory(Photo, form=MyPhotoForm)