Home > front end >  How I can show selectbox from models in my form?
How I can show selectbox from models in my form?

Time:03-08

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"  autocomplete="off">  
        {% csrf_token %}
        <div >
            <div>
                {{people.as_p}}
                <button type="submit" >apply</button>  
            </div>
        </div>
    </form>
{% endblock %}

CodePudding user response:

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"  autocomplete="off">  
        {% csrf_token %}
        <div >
            <div>
                {{form_obj.types.label_tag}}
                {{form_obj.types}}
                <button type="submit" >apply</button> 
            </div>
        </div>
    </form>
{% endblock %}
  • Related