Register data by multiple select django

Viewed 24

I'm a beginner and I was trying to create a registered data form in the database, all the fields are registered well instead of the multiple select fields.

from.py

class SavePost(forms.ModelForm):
    user = forms.IntegerField(help_text = "User Field is required.")
    title = forms.CharField(max_length=250,help_text = "Title Field is required.")
    description = forms.Textarea()
    dep = forms.Textarea()

    class Meta:
        model= Post 
        fields = ('user','title','description','file_path', 'file_path2', 'dep')

HTML

   <div class="form-group mb-3 ">
        <label for="exampleFormControlSelect2"> multiple select</label>
        <select multiple class="form-control" id="dep" value={{ post.title }}>
          <option>Process</option>
          <option>Product</option>
          <option>Equipment</option>
         
        </select>
      </div> 

    <div class="form-group mb-3 ">
        <label for="title" class="control-label">Title</label>
        <input type="text" class="form-control rounded-0" id="title" name="title" value="{{ post.title }}" required>
    </div>
    <div class="form-group mb-3">
        <label for="description" class="control-label">Description</label>
        <textarea class="form-control rounded-0" name="description" id="description" rows="5" required>{{ post.description }}</textarea>

thank you in advanced

1 Answers

You need a ChoiceField, write it as follows,

class SavePost(forms.ModelForm):

    CHOICES = [('Process', 'Process'), ('Product', 'Product'), 
    ('Equipment', 'Equipment')]
    dep = forms.ChoiceField(choices=CHOICES)

    user = forms.IntegerField(help_text = "User Field is required.")
    title = forms.CharField(max_length=250,help_text = "Title Field is required.")
    description = forms.Textarea()

    class Meta:
        model= Post 
        fields = ('user','title','description','file_path', 'file_path2', 'dep')

Check out the Django docs

You won't need to build the select in the template. I figure you are calling the for "post" from the view.py. So you will just need to create field in template with {{post.dep}}.

Related