【发布时间】: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。
任何帮助将不胜感激。提前致谢。
【问题讨论】: