使用 ModelForm 时如何在 ModelChoiceField 中设置默认选定值?

How to set default selected value in ModelChoiceField while working with ModelForm?

我正在通过 ModelForm 创建一个简单的表单,我制作了 4 个 tables,其中包括一个主 table,和 3 个子 tables,它们是main tables,一切正常。

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 ------

那么我该如何实现呢?

我的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)

我的模板文件

<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 class="red">
                {{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'

可以设置ModelChoiceFieldempty_label=… parameter [Django-doc]。从那以后我们还需要定义其余的参数,最好在ModelForm的构造函数中设置它,所以:

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