D
D
Dmitry Leonov2020-08-30 13:12:24
Django
Dmitry Leonov, 2020-08-30 13:12:24

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 = 'Настройки пользователей'


I want to display on the /dashboard/settings page for the user a set of "option name" (not editable, label tag) + "option value" (editable, textarea tag) pairs, substituting the existing values ​​from the UserSettings model into them. Everything should be displayed in one form, so that there is one "Save" button at the bottom.

When submitting the form, only those pairs should be saved in UserSettings, where the option value is not empty, or if the option already exists in the database for the user and the value is empty, then it must be deleted.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Leonov, 2020-08-30
@Lda

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 = [
            ]

Further, it is a matter of technology, to save correctly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question