“无法在没有主键的情况下强制save()中的更新"-提交编辑/更新表单时 [英] "Cannot force an update in save() with no primary key"- when submitting an edit/update form
问题描述
我有一个编辑表单,我只想更新帖子的标题",内容"和类别".为此,我在保存表单时加入了 update_fields
.但是,这有一个令人毛骨悚然的问题.当我提交表单时,Django会引发ValueError(特别是无法在没有主键的情况下强制save()中进行更新").为什么这样做,我该如何解决?
I have an edit form that I only want to update the "title", "content", and "category" of a Post. To this end, I have included update_fields
when saving the form. However, there's a wee issue with this. Django raises a ValueError (specifically "Cannot force an update in save() with no primary key") when I submit the form. Why is it doing this, and how can I fix this?
发布表格:
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')
推荐答案
似乎您正在此处重新分配帖子.在这一行;
Seems like you are re-assigning post here. In this line;
post = get_object_or_404(Post, pk = pk)
您正在从数据库中获取Post实例.然后在这一行;
You are getting a Post instance from the database. Then in this line;
post = form.save(commit=False)
您正在将post变量重新分配给一个Post的未保存实例,该实例仅填充request.POST中可用的数据.然后,当您想使用 update_fields 这样的参数保存帖子时:
You are re-assigning post variable to an unsaved instance of a Post, populated with only the data that is available in request.POST. Then, when you want to save this post with an update_fields argument like this:
post.save(update_fields = ['title', 'content', 'category', 'postURL'])
出现
ValueError的原因是,您要保存的Post实例没有ID,仅具有 request.POST
这篇关于“无法在没有主键的情况下强制save()中的更新"-提交编辑/更新表单时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!