问题描述
我所遇到的错误表明我正在尝试提交带有空必填字段的表单。
The error I am facing says that I am tring to submit a form with empty required field.
django.db.utils.IntegrityError: NOT NULL constraint failed: bug_report_bug.project_id
我的代码:-
我要做的事情是使用户报告任何项目的错误。因此,用户单击一个项目,然后获得一个错误报告表格,他/她可以在其中报告错误。每个错误都与其项目相关。
My Code:-
The thing I am trying to do is enable users report bugs for any of a project. So the user clicks on a project and then gets a bug report form where he/she can report the bug. Every bug is connected to its project.
class Bug(models.Model):
reported_by: models.ForeignKey(User, on_delete=models.CASCADE)
project = models.OneToOneField(Project, on_delete=models.CASCADE)
bug_title = models.CharField(max_length=150)
bug_description = models.TextField()
screenshot = models.ImageField(blank=True, null=True, upload_to='Bug_Reports')
date_posted = models.DateTimeField(default=timezone.now)
def __str__(self):
return 'Project: {}\nBug: {}'.format(self.project.title, self.bug_title)
def get_absolute_url(self):
return reverse("bugReport", kwargs={"pk": self.pk})
Forms.py
class BugReportForm(forms.ModelForm):
class Meta:
model = Bug
fields = ('bug_title', 'bug_description', 'screenshot')
Views.py
def bug_register(request, pk):
if request.method == 'POST':
form = BugReportForm(request.POST)
if form.is_valid():
form.project = Project.objects.get(pk=int(pk))
form.user = request.user
print(form.project.id)
form.save()
messages.success(request, f'Thankyou for Reporting! We will review your issue and revert back soon,')
return redirect('home')
else:
messages.warning(request, f'Please fill all the mandatory fields!')
else:
form = BugReportForm()
return render(request, 'bug_report/report.html', {'form': form})
您可以看到我正在URL中发送项目ID,然后在视图中接受它并查询项目类以获取对象。我无法调试我缺少的地方。
As you can see I am sending id of project in URL and then accepting it in views and querying project class to get the object. I am not able to debugg where am I lacking.
http://127.0.0.1:8000/bugreport/1/
推荐答案
以下链接包含有关如何向Django表单添加外键字段的文档和代码示例:
The following links contain documentation and code examples on how to add a foreign key field to a django form:
- https://stackoverflow.com/a/5708772/13499618
- https://docs.djangoproject.com/en/3.1/ref/forms/fields/#django.forms.ModelChoiceField
您基本上会使用 django.forms.ModelChoiceField
来允许用户选择一个默认情况下会呈现为HTML中的 select
下拉列表的。然后,提交后,表单数据将相应地发送到后端,并在 BugForm Project
的相应ID >,然后 form.save()
将起作用。
You would basically use a django.forms.ModelChoiceField
to allow your users to select a which will render as a select
dropdown in HTML by default. Then, on submit, the form data will be sent accordingly to the backend with the respective id of the Project
in the BugForm
, and form.save()
will work.
这篇关于Django IntegrityError-NOT NULL约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!