首页 > 解决方案 > 为选择字段添加额外的选项标签 - Django

问题描述

我正在使用酥脆的表格来构建我的表格。现在我想在我的字段中添加一个额外的<option>带有值的标签,timesheet_jobs即外键字段。加载所有选项后,请帮我在最后添加一个额外的<option>字段。<select>

表格.py

class ClockInForm(forms.ModelForm):

        class Meta:
            model = TimesheetEntry
            fields = ['timesheet_jobs', 'timesheet_clock_in_date', 'timesheet_clock_in_time']

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

标签: djangodjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    timesheet_jobs = self.fields['timesheet_jobs']                                    
    timesheet_jobs.choices = list(timesheet_jobs.choices)
    timesheet_jobs.choices.append(tuple(('create_new_job', 'Create New Job')))

推荐阅读