Как исправить ошибку NOT NULL constraint failed?
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Type(models.Model):
product_type = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField()
class Meta:
verbose_name_plural = 'types'
def __str__(self):
if len(self.text) > 50:
return self.text[:50] + "..."
else:
return self.text
forms.py
from django import forms
from .models import Product, Type
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name']
labels = {'name': ''}
class TypeForm(forms.ModelForm):
class Meta:
model = Type
fields = ['text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
файл views.py (проблемная зона)
def new_type(request, product_id):
product = Product.objects.get(id=product_id)
if request.method != 'POST':
form = TypeForm()
else:
form = TypeForm(data=request.POST)
if form.is_valid():
new_receipt = form.save(commit=False)
new_receipt.product = product
new_receipt.save()
return HttpResponseRedirect(reverse('vitamin_pluss:product_type', args=[product_id]))
context = {'product': product, 'form': form}
return render(request, 'vitamin_pluss/new_type.html', context)
Сообщение об ошибке
NOT NULL constraint failed: vitamin_pluss_type.product_type_id
Request Method: POST
Request URL: http://localhost:8000/new_type/4/
Django Version: 2.2.2
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: vitamin_pluss_type.product_type_id
Exception Location: C:\Users\Рома\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383
Python Executable: C:\Users\Рома\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.0
d:\python_work\python_project\vitamin_plus\vitamin_pluss\views.py in new_type
new_receipt.save() …
▼ Local vars
Variable Value
form
<TypeForm bound=True, valid=True, fields=(text)>
new_receipt
<Type: hhhh>
product
<Product: Chicken>
product_id
4
request
<WSGIRequest: POST '/new_type/4/'>