Note that there are some explanatory texts on larger screens.

plurals
  1. POSet Django ModelForm visible fields at runtime?
    primarykey
    data
    text
    <p>I have a Django model:</p> <pre><code>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) </code></pre> <p>From there, I created a ModelForm:</p> <pre><code>class CustomerForm(forms.ModelForm): class Meta: model=Customer </code></pre> <p>I'd like to be able to show pieces of the form in my template corresponding to specific information the users can change. For example, if I want to let the customers change their name, I'd like to be able to show a form that only has the fields 'first_name' and 'last_name'.</p> <p>One way to do this would be to create a ModelForm for each of the various field snippets... for the name example, it would look something like:</p> <pre><code>class CustomerFormName(forms.ModelForm): class Meta: model=Customer fields=('first_name','last_name') </code></pre> <p>This seems pretty inelegant, and inflexible. What I'd like to do is be able to specify the fields at runtime, so when I pass the dictionary from the view to the template, I can just set which fields I'd like to show. How can I set it up so that I set the fields for a form at runtime? I'd ideally like the final dictionary passed to look something like this:</p> <pre><code>{'name_change_form':CustomerFormName(&lt;form with only first_name and last_name&gt;), 'address_change_form':CustomerFormName(&lt;form with only address fields&gt;)} </code></pre> <p>Then, I know that whenever I output name_change_form.as_p, it'll have exactly the form fields that I'm looking for.</p> <p>Thoughts? Also feel free to recommend a better way to do it.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload