mirror of
https://github.com/SectorLabs/django-localized-fields.git
synced 2025-10-29 18:18:57 +03:00
Created abstract model to take care of default values
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
from typing import Callable
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.utils.text import slugify
|
||||
|
||||
from ..forms import LocalizedFieldForm
|
||||
from .localized_field import LocalizedField
|
||||
from .localized_value import LocalizedValue
|
||||
|
||||
@@ -28,6 +30,24 @@ class LocalizedAutoSlugField(LocalizedField):
|
||||
|
||||
return name, path, args, kwargs
|
||||
|
||||
def formfield(self, **kwargs):
|
||||
"""Gets the form field associated with this field.
|
||||
|
||||
Because this is a slug field which is automatically
|
||||
populated, it should be hidden from the form.
|
||||
"""
|
||||
|
||||
defaults = {
|
||||
'form_class': LocalizedFieldForm
|
||||
}
|
||||
|
||||
defaults.update(kwargs)
|
||||
|
||||
form_field = super().formfield(**defaults)
|
||||
form_field.widget = forms.HiddenInput()
|
||||
|
||||
return form_field
|
||||
|
||||
def pre_save(self, instance, add: bool):
|
||||
"""Ran just before the model is saved, allows us to built
|
||||
the slug.
|
||||
|
||||
@@ -17,9 +17,6 @@ class LocalizedField(HStoreField):
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initializes a new instance of :see:LocalizedValue."""
|
||||
|
||||
if 'default' not in kwargs:
|
||||
kwargs['default'] = LocalizedValue()
|
||||
|
||||
super(LocalizedField, self).__init__(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
|
||||
29
localized_fields/models.py
Normal file
29
localized_fields/models.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from django.db import models
|
||||
|
||||
from .fields import LocalizedField, LocalizedValue
|
||||
|
||||
|
||||
class LocalizedModel(models.Model):
|
||||
"""A model that contains localized fields."""
|
||||
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initializes a new instance of :see:LocalizedModel.
|
||||
|
||||
Here we set all the fields that are of :see:LocalizedField
|
||||
to an instance of :see:LocalizedValue in case they are none
|
||||
so that the user doesn't explicitely have to do so."""
|
||||
|
||||
super(LocalizedModel, self).__init__(*args, **kwargs)
|
||||
|
||||
for field in self._meta.get_fields():
|
||||
if not isinstance(field, LocalizedField):
|
||||
continue
|
||||
|
||||
value = getattr(self, field.name, None)
|
||||
if not isinstance(value, LocalizedValue):
|
||||
value = LocalizedValue()
|
||||
|
||||
setattr(self, field.name, value)
|
||||
Reference in New Issue
Block a user