Django ModelAdmin save method not executing
I have a custom ModelForm class and ModelAdmin class and for some reason my save_model method will not execute.
Ill show both classes i currently have in admin.py. all functions (search, filter, hiding fields, delete) currently work correctly except for saving a new entry...
here is my form:
class SeasonalityOriginalsForm(forms.ModelForm):
# defining the input fields that should be hidden
class Meta:
model = SeasonalitiesCalculated
fields = '__all__'
widgets = {
'has_been_reviewed': forms.HiddenInput(),
'user': forms.HiddenInput(),
'source_importance_0least_to_10most': forms.HiddenInput(),
'internal_id': forms.HiddenInput(),
}
### this defines a dropdown selector field for object_id
### instead of copy-pasting the UUID from another adminmodel page, which could bring errors
### admins can now select the country or admin_zone_1 with the right granularity by selecting location name
### an issue is that this is a choicefield, not a model choicefield.
### this issue is solved in the save_model method in the ModelAdmin class.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
logger.debug(f'self model info: {type(self.fields)}')
countries = Countries.objects.filter(level_of_seasonal_area_granularity='country')
admin_zones1 = AdminZones1.objects.filter(country__level_of_seasonal_area_granularity='admin_1')
choices = [(obj.public_id, str(obj)) for obj in countries] + [(obj.public_id, str(obj)) for obj in admin_zones1]
self.fields['object_id'] = forms.ChoiceField(choices=[])
self.fields['object_id'].choices = choices
logger.debug(f'self model info2: {self.fields}')
### here are the visible input fields of the
object_id = forms.ChoiceField(choices=[])
content_type = forms.ModelChoiceField(
queryset=ContentType.objects.filter(model__in=['countries', 'adminzones1']),
widget=forms.Select(attrs={'class': 'form-control'})
)
seasonality = forms.DecimalField(min_value=Decimal('0'), max_value=Decimal('1'), decimal_places=1)
Here is my ModelAdmin class:
### define SeasonalityOriginalsAdmin for ContributorAdmin
class SeasonalityOriginalsAdmin(admin.ModelAdmin):
form = SeasonalityOriginalsForm
### modifying the search method for the searchfield
def get_search_results(self, request, queryset, search_term):
#... skipping this for now
### defining that existing fields are readonly
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return [field.name for field in self.model._meta.fields]
return []
### not allowing delete permissions
def has_delete_permission(self, request, obj=None):
return False
### save method modification
def save_model(self, request, obj, form, commit=True):
logger.debug(f'tried several logs and print statements here but none show')
location_name = self.cleaned_data['object_id']
location = Countries.objects.filter(country_name=location_name).first() or AdminZones1.objects.filter(admin_zone_name=location_name).first()
self.object_id = location.pk
max_internal_id = self.model.objects.filter(internal_id__isnull=False).aggregate(Max('internal_id'))['internal_id__max']
obj.internal_id = max_internal_id + 1 if max_internal_id is not None else 1
if request.user.is_contributor:
obj.source_importance_0least_to_10most = 10
else:
obj.source_importance_0least_to_10most = 3
obj.user = request.user
return super().save(commit)
### defining the displayed rows, fields and search field
list_per_page = 20
list_display = ('ingredient_original', 'content_object','seasonality')
search_fields = ('seasonality_originals__public_id', 'ingredient_original__ingredient_original_name_en',)
ordering = ('ingredient_original',)
something must be super wrong with my save method because it wont even execute any logs that i place in the codeblock...
my model itself does not have any custom save method
thanks in advance for your help!!!!!