我一直在尝试允许员工用户将作业发布到数据库,但是我不断遇到上述问题。我尝试过设置data['id'] = 0/''以及删除表和 makemigrations/migrate。models.pyfrom django.db import modelsfrom teachers.models import Teacherclass 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.titleform.pyfrom django import formsclass 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.pydef 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')
3 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
您是否尝试使用 data['teacher'] = request.user 而不是 data['teacher'] = request.user.username ?
SMILET
TA贡献1796条经验 获得超4个赞
我很欣赏这些答案。我设法通过将表单转换为模型表单来解决这个问题,因为该表单模型更适合这种情况,因为模型字段直接映射到输入。
新形式.py
from homework.models import Homework
from django import forms
class 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'}),
}
添加回答
举报
0/150
提交
取消