Answer the question
In order to leave comments, you need to log in
How to create a dynamic user panel settings form in Django 3.1?
Good afternoon, I'm stuck with formset, maybe this is not what I need at all.
I need to create a dynamic user settings form in his control panel.
I have 2 models:
class Settings(models.Model):
INPUT = 'TextInput'
TEXTAREA = 'Textarea'
WIDGET_CHOICES = [
(INPUT, 'Input'),
(TEXTAREA, 'Textarea')
]
slug = models.CharField(max_length=60, unique=True, default=None)
name = models.CharField(max_length=60)
description = models.CharField(max_length=600)
widget = models.CharField(max_length=10, choices=WIDGET_CHOICES, default=INPUT)
class Meta:
verbose_name = 'Настройки'
verbose_name_plural = 'Настройки'
class UserSettings(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
setting = models.ForeignKey(Settings, on_delete=models.CASCADE)
value = models.TextField()
class Meta:
verbose_name = 'Настройки пользователей'
verbose_name_plural = 'Настройки пользователей'
Answer the question
In order to leave comments, you need to log in
Decided like this:
class UserSettingsForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserSettingsForm, self).__init__(*args, **kwargs)
settings_arr = Settings.objects.all()
for setting in settings_arr:
self.fields[setting.pk] = forms.CharField(
required=True,
widget=getattr(forms, setting.widget),
label=setting.name,
help_text=setting.description
)
class Meta:
model = Settings
fields = [
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question