1
我有一個名爲Thoughts的模型,它有很多評論,所以我用一個主鍵定義了一個Comment部分。Django:實現評論funcionality時出現'NOT NULL約束失敗'
from django.db import models
class Thoughts(models.Model):
name = models.CharField(max_length=30)
thought = models.CharField(max_length=500)
class Comments(models.Model):
name = models.CharField(max_length=30)
comment = models.CharField(max_length=200)
original_post = models.ForeignKey(Thoughts)
這裏是我的forms.py它定義了一個註釋字段:
class CommentForm(forms.Form):
name = forms.CharField(max_length=30)
comment = forms.CharField(max_length=500)
class Meta:
model = Comments
fields = ('name','comment',)
處理表單數據的視圖:
def thought(request, thought_num):
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
c =Comments.objects.create(name=form.cleaned_data['name'],
comment=form.cleaned_data['comment'])
c.save()
else:
form = CommentForm()
return render(request, 'thought.html', {'form': form})
當我嘗試在輸入值窗體,我得到這個錯誤:
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: thoughts_comments.original_post_id
我懷疑它與這些行做:
c = Comments.objects.create(name=form.cleaned_data['name'],
comment=form.cleaned_data['comment'])
c.save()
後的數據經過精細沒有那些線(就是不會創建註釋),這樣的東西與模型可能?我一直堅持這一段時間,我對django的web開發相當陌生。
感謝您的時間,
添加了字段,同樣的錯誤 – Ecko
你有'migrate'嗎? –
不!它現在可用,評論顯示在localhost/admin中。出於好奇,任何理由爲什麼這些領域是必要的。 – Ecko