Entries tagged 'Django'
Compact table names with Django RAPID
The last couple of Django applications that I’ve built have used the Django RAPID Architecture which I think fits better with how a larger web application grows and evolves. Part of it is putting all of the models into their own data app, but in doing so I like to avoid having the data_ prefix on every table. Putting this in app/data/__init__.py gets rid of that. This is basically the example from the manual except using removeprefix() (added in Python 3.9) instead of a regex.
from django.db.models.signals import class_prepared
from django.dispatch import receiver
@receiver(class_prepared)
def remove_table_prefix(sender, **kwargs):
sender._meta.db_table = sender._meta.db_table.removeprefix("data_")
Using AutocompleteSelect in a Django Admin form
I was building an action for a Django Admin changelist view to allow associating models to a related model. But to select the related model on the form, a regular ModelChoiceField would load all of the possibilities to populate the <select> form field, which was pretty terrible when there are thousands to tens of thousands of options.
Within the change view of the model, you can just add that field to autocomplete_fields and Django has a nice built-in widget that uses a Select2-style form input. It is called AutocompleteSelect. I couldn't find any examples of someone using this widget outside of it being pulled in by autocomplete_fields but it ended up being surprisingly easy.
Here is a rough example of the form definition at the heart of the solution:
from django import forms
from django.contrib.admin.widgets import AutoCompleteSelect
from .models import Model, RelatedModel
class BatchAssociationForm(forms.Form):
related_field = forms.ModelChoiceField(
queryset=RelatedModel.objects.all(),
label="Related",
help_text="Select the object to relate to",
widget=AutocompleteSelect(Model.related_field.field, admin.site)
)
No extra package necessary. I am using Django 5.2, and I have no idea if this will work with earlier versions.
A while back, I wanted to build a filter for a changelist admin that used the autocomplete widget for selecting the value(s) to filter on. Now that I cracked it for a form, maybe I should revisit that idea.