im试图使用用户的ModelForm输入来更新模型实例的特定字段(非PK字段),例如博客模型
class Post(models.Model):
STATUS_CHOICES = [
('draft','Draft'),
('published','Published')
]
postId = models.AutoField(primary_key=True)
title = models.CharField(max_length=50,unique=True)
slug = models.SlugField(max_length=50)
body = models.TextField()
status = models.CharField(max_length=20,choices=STATUS_CHOICES,default='draft')
date = models.DateField(auto_now_add=True)
-----------------------------------------------------------------------
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title','body','status']
-----------------------------------------------------------------------
def edit(request,slug):
template = 'blog/post_edit.html'
post = get_object_or_404(Post,slug=slug)
form = PostForm(request.POST or None,instance=post)
if request.method == 'POST':
if form.is_valid():
form.save()
return render(request,template,{'form':form})
我看到的问题是数据库正在尝试使用相同的postId PK插入新值!
我还尝试在同一个post实例中使用cleaned_data,并且总是得到相同的错误