S
S
stayHARD2016-03-19 15:30:45
Django
stayHARD, 2016-03-19 15:30:45

Django Admin Panel. How to display fields dynamically based on a variable in settings.py?

Hi {{ user.username }}.
Need your help/advice on implementing custom fields in Django admin.
Essence:
Based on certain values, add additional fields to the object (model) when it is created in the admin panel.
Input:
Variable in settings.py:

TARGET_LANGUAGES = (
    'ru', 'Russian',
    'es', 'Spanish',
)

Topic model in models.py:
class Topic(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category)

    def __unicode__(self):
        return self.name

LocalaziedTopic model in models.py:
class LocalizedTopic(models.Model):
    topic = models.ForeignKey(Topic)
    content = models.CharField(max_length=255)
    lang = models.ForeignKey(Language, default='en')

    def __unicode__(self):
        return self.topic.name

Task:
When creating a new Topic, issue fields:
- name
- category
and then as many fields as there are now languages ​​in settings (for example, for the current ones, those above)
will be:
- localized_topic_name_russian
- localized_topic_name_spanish
Save as one Topic object and two LocalizedTopic objects.
What will be the considerations?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2016-03-19
@sergey-gornostaev

Do you want to make LocalizedTopic inline for Topic? Their number can be limited by setting max_num = len(TARGET_LANGUAGES)

class LocalizedTopicAdmin(admin.StackedInline):
    model = LocalizedTopic
    max_num = len(settings.TARGET_LANGUAGES)

class TopicAdmin(admin.ModelAdmin):
    inlines = [LocalizedTopicAdmin]

S
Sergey, 2016-03-19
@bogdanov-s

from django.conf import settings

for lang in settings.TARGET_LANGUAGES:
    # Add custom field...

A
Andrey K, 2016-03-19
@mututunus

Use https://github.com/deschler/django-modeltranslation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question