Home > OS >  how to set default selected value in ModelChoiceField while working with ModelForm?
how to set default selected value in ModelChoiceField while working with ModelForm?

Time:02-13

I am creating a simple form through ModelForm,i have made 4 tables which consists of one main table, and 3 sub tables which is the foreign keys of main tables,everything is working perfect.

But I want that there must be selected value in form which will show in the frontend by default.

by default it is showing -------- in select tag of html but i want that it will show some label like in my case: it will be better if it shows Select Job Description by default rather than ------

so how can i implement that?

My forms.py

from django import forms
from django.utils.translation import gettext_lazy as _
from numpy import empty
from .models import SignUpModel


class SignUpForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'First Name'}), required=True, error_messages={'required': 'First Name is required'})
    last_name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Last Name'}), required=True, error_messages={'required': 'Last Name is required'})
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'placeholder': 'Email Address'}), required=True, error_messages={'required': 'Email Address is required'})

    class Meta:
        model = SignUpModel
        fields = ['first_name', 'last_name', 'email', 'password',
                  'company_name', 'job', 'mobile_no', 'country', 'state']
        widgets = {
            'password': forms.PasswordInput(attrs={'placeholder': 'Password'}),
            'company_name': forms.TextInput(attrs={'placeholder': 'Company Name'}),
            'mobile_no': forms.NumberInput(attrs={'placeholder': 'Mobile Number'}),
        }
        error_messages = {
            'password': {
                'required': _('password is required')
            },
            'mobile_no': {
                'required': _('Mobile Number is required')
            },
            'company_name': {
                'required': _('Company Name is required')
            },
            'job': {
                'required': _('Job description must be selected')
            },
            'state': {
                'required': _('State Name is required')
            }
        }

Models.py

    from django.db import models
    from django.contrib.auth.models import User


    class JobType(models.Model):
        job_name = models.CharField(max_length=50)

        def __str__(self):
            return self.job_name
    class Country(models.Model):
        country_name = models.CharField(max_length=50)
        def __str__(self):
            return self.country_name

    class IndianStates(models.Model):
        state_name = models.CharField(max_length=30)
        def __str__(self):
            return self.state_name


    class SignUpModel(User):
        company_name = models.CharField(max_length=80)
        job = models.ForeignKey(JobType, on_delete=models.CASCADE)
        mobile_no = models.PositiveIntegerField()
        country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=True)
        state = models.ForeignKey(IndianStates, on_delete=models.CASCADE)

my template file

<body>

    {% if form %}
    <form method="POST" novalidate>
        {% csrf_token %}
        {% if form.non_field_errors %}
        {% for error in form.non_field_errors  %}
        <div>
            {{error}}

        </div>
        {% endfor %}
        {% endif %}
        {% for field in form %}
        <div>
            {{field}}
            {% for error in field.errors  %}
            <div >
                {{error}}

            </div>
            {% endfor %}
        </div>
        {% endfor %}

        <input type="submit" value="Register">

    </form>
    {% endif %}
    
</body>

Views.py

from django.shortcuts import render
from django.views.generic.base import TemplateView
from . forms import SignUpForm
from django.views.generic.edit import CreateView


class HomeTemplateView(CreateView):
    template_name = 'home/index.html'
    form_class = SignUpForm
    success_url = '/thanks/'


class CreatedThanksTemplate(TemplateView):
    template_name = 'home/thanks.html'

CodePudding user response:

You can set the empty_label=… parameter [Django-doc] of the ModelChoiceField. Since then we need to define the rest of the parameters as well, it might be better to set it in the constructor of the ModelForm, so:

class SignUpForm(forms.ModelForm):
    # …
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['job'].empty_label = 'Select Job Description'
    
    class Meta:
        model = SignUpModel
        # …
  • Related