Set visible fields of Django ModelForm at runtime?

I have a Django model:

class Customer(models.Model):
  first_name=models.CharField(max_length=20,null=True, blank=True)
  last_name=models.CharField(max_length=25,null=True, blank=True)
  address=models.CharField(max_length=60,null=True, blank=True)
  address2=models.CharField(max_length=60,null=True, blank=True)
  city=models.CharField(max_length=40,null=True, blank=True)
  state=models.CharField(max_length=2,null=True, blank=True)

From there I created ModelForm:

class CustomerForm(forms.ModelForm):
  class Meta:
    model=Customer

I would like to be able to show parts of the form in my template that correspond to specific information that users can change. For example, if I want clients to change their name, I would like to be able to display a form that has only the "first_name" and "last_name" fields.

One way to do this would be to create a ModelForm for each of the various fragments of the field ... for an example of a name, it would look something like this:

class CustomerFormName(forms.ModelForm):
  class Meta:
    model=Customer
    fields=('first_name','last_name')

. , , , , , , . , ? , , :

{'name_change_form':CustomerFormName(<form with only first_name and last_name>), 'address_change_form':CustomerFormName(<form with only address fields>)}

, , name_change_form.as_p, , .

? .

+3
1
from django.forms import ModelForm
from wherever import Customer
def formClassFactory(model,fields):
  ff = fields
  mm = model
  class formClass(ModelForm):
    class Meta:
      model  = mm
      fields = ff
  return formClass
form_class = formClassFactory( ('first_name','last_name') )
+4

Source: https://habr.com/ru/post/1755213/


All Articles