0

I hope the title of this question is as it should be based on this explanation below.

I have a model as below:

class Setting(models.Model):
    TYPE_CHOICES = (
        ('CONFIG', 'Config'),
        ('PREFS', 'Prefs'),
    )

    attribute = models.CharField(max_length=100, unique=True)
    value = models.CharField(max_length=200)
    description = models.CharField(max_length=300)

    type = models.CharField(max_length=30, choices=TYPE_CHOICES)
    is_active = models.BooleanField(_('Active'), default=True)

I use this to save settings. I have don't know all settings in advance and they can change in future. So I decided to save attributes and their values in this model instead of creating columns for each setting(attribute in the model).

Now the problem I am facing is how do I present form with all attributes as fields so that a user can fill in appropriate values.

Right now, as you can see, form shows columns 'Attribute' and "Value" as labels. I would like it to show value of column 'Attribute' as label and column 'Value' as field input.

For example, in Setting model I have this:
Attribute ------------ Value
'Accept Cash' ---------- 'No'

I would like to appear this on form as
<Label>: <Input>
'Accept Cash': 'No'

I think I will have to build form fields from the database(Setting model). I am new to this and have no idea how to begin with it any example or link to tutorial that would help me get started will be much appreciated.

Thank you

Newbie
  • 343
  • 2
  • 13

1 Answers1

0

you can define a model form based on your Settings model. Check the django documentation on Django Model Forms. The basic definition of the model form should be something like this

Define a forms.py file in your current django app and put the following code in it.

from django import forms
from .models import Settings

class SettingsForm(forms.ModelForm):
    class Meta:
        model = Settings
        fields = ['the fields you want to add'] # or use '__all__' without the parentheses for all fields

Then in your views.py file navigate to the function which renders the page containing the form and add this to it

from .forms import SettingsForm

def your_function(request):
   ....

   context = {
       ....
       'form':SettingsForm()
   }
   return render(request, 'template_name.html', context)

Now in your template add the form using

........

{{ form }}

.......
  • I looking for a way to build form fields based on database records. I know how to make form based on model schema. – Newbie Feb 19 '21 at 12:45
  • Do you want to add choices according to your data in database. If so check out this post https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field – Mitrajeet Golsangi Feb 20 '21 at 11:51