how to insert object_list inside the select of the form in the Django 2.1 template

Asked

Viewed 285 times

0

how can I insert a list of my database into the select form?

html template.

<div class="form-group">
    <label for="{{ form.id_departamento }}">Nome departamento</label>
    <select name="{{ form.id_departamento }}" required="" class="form-control" id="{{ form.id_departamento }}" multiple="">
        <option value="">------</option>
        <option value="{{ form.id_departamento }}">{{ form.id_departamento }}</option>
    </select>
</div>

py.models

class Funcionario(models.Model):
    nome = models.CharField(max_length=100, help_text='Nome completo do funcionário')
    funcao = models.CharField(max_length=100, help_text='Função na empresa')
    user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='funcionario')
    departamentos = models.ManyToManyField(Departamento, related_name='funcionario')
    empresa = models.ForeignKey(
        Empresa, on_delete=models.PROTECT, null=True, blank=True)

1 answer

0

You could use Django’s Modelform, creating a class for Funcionario, and not have to go through these problems.

class Funcionario(forms.ModelForm):    
    class Meta:
        model = Funcionario
        fields = ['nome', 'funcao', 'user', 'departamentos', 'empresa']
        widgets = {
            'nome': forms.TextInput(attrs={'class': 'form-control'}), 
            'funcao': forms.TextInput(attrs={'class': 'form-control'}), 
            'user': forms.TextInput(attrs={'class': 'form-control', 'type': 'hidden'}), 
            'departamentos': forms.SelectMultiple(attrs={'class': 'form-control'}), 
            'empresa': forms.Select(attrs={'class': 'form-control'})
        }

And in the example of your template:

<div class="form-group">
    <label for="departamentos">Nome departamento</label>
    {{ form.departamentos }}
</div>

Please tell me if this has solved your problem.

  • I didn’t get the class part right, I create a Forms.py file and include the code in it?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.