Reputation: 1736
I am new to django and trying to create a simple form. I am using django 3.1.2 and python 3.8.3.
Below is my code
model
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'
form
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']
view
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})
I am getting below error whenever try to save data
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).
also, print(form.cleaned_data['categoryid'])
statement of fill_timesheet view is printing category name instead of categoryid.
My question is how can I link categoryid of form with categoryid of model. I want to show drop down of category on web page and want to insert categoryid in table.
Any help would be appreciated. Thanks in advance.
Upvotes: 0
Views: 989
Reputation: 7330
I think it's because you are not including categoryid
in your Meta.fields
of the TimesheetForm
class
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']
Upvotes: 2