Darwin
Darwin

Reputation: 2037

How I can show selectbox from models in my form?

How I can show selectbox from models in my form. Output for below code does not show options for selectbox.

#models.py

class Reg(models.Model):
    options = (
        ('one', 'option1'),
        ('two', 'option2'),
    )
    types       =   models.CharField(max_length=30, choices=options,null=True)
    company     =   models.CharField(max_length=50,null=True)

#form.py

from django import forms  
from .models import Reg
class Regform(forms.ModelForm):  
    class Meta:  
        model = Reg
        fields = ['types','company']


    types = forms.CharField(
        widget=forms.Select(
            attrs={'class': 'form-control'}
        ),
        label="Type",
    )

templatefie.html

{% load static %}

{% block main %}
    <form method="post" class="post-form" autocomplete="off">  
        {% csrf_token %}
        <div class="row col-md-4 m-auto">
            <div>
                {{people.as_p}}
                <button type="submit" class="save btn btn-primary mt-5">apply</button>  
            </div>
        </div>
    </form>
{% endblock %}

Upvotes: 0

Views: 59

Answers (1)

B.Anup
B.Anup

Reputation: 585

Labels and widgets can be defined separately.

Class RegForm(forms.ModelForm):
    class Meta:
        model = Reg
        fields = ['types','company']

    labels = {
        'types': 'Types',
        'company': 'Company'
    }

    widgets = {
        'types': Select(attrs={'class':'form-control'})
    }

Create a view function that creates instance of the "Reg" modelform and pass in context to the template context = {'form_obj':Regform()}

{% load static %}
{% block main %}
    <form method="post" class="post-form" autocomplete="off">  
        {% csrf_token %}
        <div class="row col-md-4 m-auto">
            <div>
                {{form_obj.types.label_tag}}
                {{form_obj.types}}
                <button type="submit" class="save btn btn-primary">apply</button> 
            </div>
        </div>
    </form>
{% endblock %}

Upvotes: 1

Related Questions