I am writing my first Django application. I have the following database model:
class Person(models.Model):
first_name = models.CharField(max_length = 100)
last_name = models.CharField(max_length = 100)
class InformationType(models.Model):
name = models.CharField(max_length = 100)
class Information(models.Model):
person = models.ForeignKey(Person)
info_type = models.ForeignKey(InformationType)
info = models.CharField(max_length = 200)
I want to create some inline strings in Django Admin (class PersonAdmin (ModelAdmin)), breaking the information model by type and dynamically. I also want to hide (exclude) the "info_type" field from the user interface and automatically fill it with the corresponding value.
I can dynamically create rows with information "Information" filtered by "info_type", but hiding this field in the user interface makes it empty when saved.
How can i do this? Is it possible to make a hidden field? Or where should I store the value of "info_type"?
I searched googled and found nothing =)
:
. "":
class Information(models.Model):
def save(self, *args, **kwargs):
self.info_type = self.fixed_info_type
super(Information, self).save(*args, **kwargs)
... :
class InformationManager(models.Manager):
def __init__(self, info_type, *args, **kwargs):
self.__info_type = info_type
super(InformationManager, self).__init__(*args, **kwargs)
def get_query_set(self, *args, **kwargs):
return super(self.__class__, self).get_query_set(*args, **kwargs).filter(info_type=self.__info_type)
class PhoneInformation(Information):
fixed_info_type = 'PHONE'
objects = InformationManager(fixed_info_type)
class Meta:
proxy = True
class EmailInformation(Information):
fixed_info_type = 'EMAIL'
objects = InformationManager(fixed_info_type)
class Meta:
proxy = True
admin.py:
from contacts.models import Person, PhoneInformation, EmailInformation
class PersonAdmin(admin.ModelAdmin):
__inlines = []
class classproperty(property):
def __get__(self, instance, owner):
return super(self.__class__, self).fget.__get__(None, owner)()
@classproperty
@classmethod
def inlines(cls):
def get_inline(InformationModel):
class Inline(admin.TabularInline):
model = InformationModel
exclude= ['info_type']
return Inline
if not cls.__inlines:
for InformationModel in [PhoneInformation, EmailInformation]:
cls.__inlines.append(get_inline(InformationModel))
return cls.__inlines
, DRY. , InlineAdmin. .