【问题标题】:Map Form Fields with Model Fields in Django在 Django 中使用模型字段映射表单字段
【发布时间】:2020-10-15 09:05:16
【问题描述】:

我是 django 的新手,正在尝试创建一个简单的表单。我正在使用 django 3.1.2 和 python 3.8.3。

下面是我的代码
模型

class Category(models.Model):
    categoryid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)

    class Meta:
        managed = False
        db_table = 'category'

    def __str__(self):
        return u'{0}'.format(self.name)


class Timesheet(models.Model):
    timesheetid = models.AutoField(primary_key=True)
    categoryid = models.ForeignKey(Category, models.DO_NOTHING, db_column='categoryid')
    summary = models.CharField(max_length=100)
    description = models.CharField(max_length=1000, blank=True, null=True)
    logdate = models.DateField()
    minutes = models.IntegerField(blank=True, null=True)
    addeddate = models.DateTimeField(default=datetime.now())
    modifieddate = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'timesheet'

表格

class TimesheetForm(forms.ModelForm):
    categoryid = forms.ModelChoiceField(queryset=Category.objects.all().order_by('name'),
                                                         empty_label="Select Category",required=True,label='Category',to_field_name='categoryid')
    class Meta:
        model = Timesheet
        fields = ['summary','description','logdate','minutes']

查看

def fill_timesheet(request):
    form = TimesheetForm()

    if request.method == "POST":
        form = TimesheetForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data['summary'])
            print(form.cleaned_data['description'])
            print(form.cleaned_data['categoryid'])
            form.save(commit=True)
            return index(request)
        else:
            print('ERROR FORM INVALID')

    return render(request,'app_timesheet/timesheet.html',{'timesheet_form':form})

下面是我的网页

每次尝试保存数据时都会出现以下错误

null value in column "categoryid" violates not-null constraint
DETAIL:  Failing row contains (32, null, test data, test description, 2020-10-13, 5, 2020-10-15 14:25:40.57836, null).

另外,fill_timesheet 视图的print(form.cleaned_data['categoryid']) 语句正在打印类别名称而不是类别ID。 我的问题是如何将表单的 categoryid 与模型的 categoryid 链接起来。我想在网页上显示类别的下拉菜单,并想在表格中插入 categoryid。

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: python django


    【解决方案1】:

    我认为这是因为您没有在 TimesheetForm 类的 Meta.fields 中包含 categoryid

     
    class TimesheetForm(forms.ModelForm):
        categoryid = forms.ModelChoiceField(queryset=Category.objects.all().order_by('name'),
                                                             empty_label="Select Category",required=True,label='Category',to_field_name='categoryid')
        class Meta:
            model = Timesheet
            fields = ['summary','description','logdate','minutes','categoryid']
    

    【讨论】:

    • 在字段列表中添加 categoryid 后它起作用了。我认为我们不需要添加单独定义的字段。
    猜你喜欢
    • 1970-01-01
    • 2022-08-03
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多