我是django的初学者,请帮帮我,我已经试了2个小时了,非常感谢!
<我在/ IntegrityError /431cdef3-d9e7-4abd-bf53-eaa7b188d0fd上得到了这个django错误博客>
python #视图
from django.shortcuts import render
from .models import Blog
from .forms import CommentForm
def home(request):
template = 'blogs/home.html'
blogs = Blog.objects.all()
context = {'blogs':blogs}
return render(request, template, context)
def blog(request, pk):
template = 'blogs/blog.html'
blog = Blog.objects.get(pk=pk)
context = {'blog':blog}
if request.method == 'POST':
form = CommentForm(request.POST)
form.save()
else:
form = CommentForm()
context['form'] = form
return render(request, template, context) #表单
from django.forms import ModelForm
from .models import Comment
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['description']#机型
from django.db import models
import uuid
class Blog(models.Model):
header = models.CharField(max_length=200)
posts = models.TextField(null=True)
footer = models.TextField(null=True, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.header
class Comment(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments')
description = models.TextField(blank=True, null=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.description `发布于 2021-08-03 02:45:53
试试这个:
def blog(request, pk):
template = 'blogs/blog.html'
blog = Blog.objects.get(pk=pk)
context = {'blog':blog}
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False) # don't save the comment yet
comment.blog = blog # assign the blog
comment.save() # then save
else:
form = CommentForm()
context['form'] = form
return render(request, template, context) 在将评论提交到数据库之前,首先将博客添加到评论中。
发布于 2021-08-03 02:18:20
您没有使用Foreignkey key值进行添加。试试这个吧。
def blog(request, pk):
template = 'blogs/blog.html'
blog = Blog.objects.get(pk=pk)
context = {'blog':blog}
if request.method == 'POST':
form = CommentForm(request.POST, instance=blog)
if form.is_valid():
form.save()
else:
form = CommentForm(instance=blog)
context['form'] = form
return render(request, template, context) https://stackoverflow.com/questions/68629523
复制相似问题