I am trying to create a dynamic form after checking some condition in the view and i am not sure how to approach it. How do i populate the fields attribute in the forms Meta class from my views?
Below are my views.py and my forms.py files.
views.py
How do i populate the fields list in forms.py from my views?
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django import forms
from .models import Master, Label, Assosiative
from .forms import LabelForm, MzasterForm, AssosiativeForm
def master(request,pk):
associate = get_object_or_404(Assosiative, pk=pk)
form = MasterForm(request.POST or None)
if associate.short_text1 == 1:
form.fields['short_text1'] = forms.CharField(label='Short text 1')
if associate.short_text2 == 1:
form.fields['short_text2'] = forms.CharField(label='Short text 2')
if associate.short_text3 == 1:
form.fields['short_text3'] = forms.CharField(label='Short text 3')
if associate.short_text4 == 1:
form.fields['short_text4'] = forms.CharField(label='Short text 4')
if associate.num_field1 == 1:
form.fields['num_field1'] = forms.CharField(label='Number field 1')
if associate.num_field2 == 1:
form.fields['num_field2'] = forms.CharField(label='Number field 2')
if form.is_valid():
try:
short_text1 = form.cleaned_data['short_text1']
short_text2 = form.cleaned_data['short_text2']
short_text3 = form.cleaned_data['short_text3']
short_text4 = form.cleaned_data['short_text4']
num_field1 = form.cleaned_data['num_field1']
num_field2 = form.cleaned_data['num_field2']
form.save()
except Exception, ex:
return HttpResponse("Error %s" %str(ex))
return render(request, 'master.html', {'form':form,})
forms.py
I am not sure what to do here so that i can populate the fields from my views
def masterForm(fields_list, *args, **kwargs):
class MasterForm(forms.ModelForm):
class Meta:
model = Master
fields = fields_list
def __init__(self):
super(MasterForm, self).__init__(*args, **kwargs)
return MasterForm()
joke = masterForm(('short_text1',))