Django TypeError:字段“id”需要一个数字

我一直在尝试允许员工用户将作业发布到数据库,但是我不断遇到上述问题。我尝试过设置data['id'] = 0/''以及删除表和 makemigrations/migrate。


models.py


from django.db import models

from teachers.models import Teacher



class Homework(models.Model):


  title = models.CharField(max_length=100)

  descripiton = models.CharField(max_length=500)

  due = models.DateField()

  teacher = models.OneToOneField(

      Teacher, null=True, blank=True, on_delete=models.CASCADE)


  def __str__(self):

    return self.title

form.py


from django import forms



class DateInput(forms.DateInput):

    input_type = 'date'



class HomeworkForm(forms.Form):

    title = forms.CharField(label='Title', max_length=100)

    descripiton = forms.CharField(label='Descripiton', max_length=500)

    due = forms.DateField(label='Due', widget=DateInput)

views.py


def homework(request):

    if request.user.is_authenticated & request.user.is_staff:

        if request.method == 'POST':

            data = request.POST.copy()

            data['teacher'] = request.user.username

            request.POST = data

            print(request.POST)

            form = HomeworkForm(request.POST)

            if form.is_valid():

                post = Homework(form)

                post.save()

                messages.info(request, 'Form sent')

                print('worked')

                return render(request, 'index/index.html')

            else:

                print('error in form')

                form = HomeworkForm()

                return render(request, 'dashboard/setHomework.html', {'form': form})

        else:

            form = HomeworkForm()

            return render(request, 'dashboard/setHomework.html', {'form': form})

    else:

        return redirect('index')


守着星空守着你
浏览 141回答 3
3回答

墨色风雨

您是否尝试使用 data['teacher'] = request.user 而不是 data['teacher'] = request.user.username ?

翻阅古今

你不需要使用request.POST.copy(),request.POST已经是一本字典了。

SMILET

我很欣赏这些答案。我设法通过将表单转换为模型表单来解决这个问题,因为该表单模型更适合这种情况,因为模型字段直接映射到输入。新形式.pyfrom homework.models import Homeworkfrom django import formsclass HomeworkForm(forms.ModelForm):    class Meta:        model = Homework        fields = ['title', 'description', 'due']        widgets = {            'due': forms.DateInput(format=('%m/%d/%Y'), attrs={'label': 'due date', 'type': 'date'}),        }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python