我有一个编辑表单,我只想更新帖子的“标题”,“内容”和“类别”。为此,我在保存表单时包括了update_fields
。但是,这有一个小问题。当我提交表单时,Django引发ValueError(特别是“无法在没有主键的情况下强制save()中进行更新”)。为什么这样做,我该如何解决?
发布表格:
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key in ['postTitle', 'postContent', 'category']:
self.fields[key].widget.attrs.update({'class': 'form-control'})
self.fields['content'].widget.attrs.update(width='100px', height='50')
class Meta:
model = Post
fields = ('title', 'content', 'category')
发布模型:
class Post(models.Model):
title = models.CharField(max_length = 100)
URL = models.SlugField() # slug for url
content = models.TextField()
author = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'posts') # id of author
category = models.CharField(max_length = 9, default = 'General') # category the post is in
creationDate = models.DateTimeField()
编辑视图:
def editPost(request, pk):
if request.method == 'GET':
post = get_object_or_404(Post, pk = pk)
if post.author == request.user:
form = PostForm(instance = post)
return render(request, 'editPost.html', {'form': form, 'post': post})
else:
return redirect('viewPost', pk = pk, postURL = post.postURL)
if request.method == 'POST':
post = get_object_or_404(Post, pk = pk)
form = PostForm(request.POST)
if post.author == request.user:
if form.is_valid():
post = form.save(commit=False)
post.URL = slugify(post.postTitle)
post.save(update_fields = ['title', 'content', 'category', 'postURL'])
return redirect('viewAll')
答案 0 :(得分:1)
似乎您正在此处重新分配帖子。在这一行;
post = get_object_or_404(Post, pk = pk)
您正在从数据库中获取Post实例。然后在这一行;
post = form.save(commit=False)
您正在将post变量重新分配给未保存的Post实例,该实例仅填充request.POST中可用的数据。然后,当您想使用 update_fields 这样的参数保存帖子时:
post.save(update_fields = ['title', 'content', 'category', 'postURL'])
出现ValueError的原因是,您要保存的Post实例没有ID,仅具有 request.POST
中可用的ID。