I have an edit view for when a user wants to edit a Post:
def edit(request, id):
post = get_object_or_404(Post, id=id)
edit_form = PostForm(request.POST or None, instance=post)
if edit_form.is_valid():
instance = edit_form.save(commit=False)
instance.save(update_fields=['content'])
return HttpResponseRedirect('/')
else:
print(edit_form.errors)
edit_form = PostForm(instance=post)
context = {
'edit_form': edit_form,
'form_post': post
}
return render(request, 'edit.html', context)
When a user edits a Post, I only want them to be able to edit 1 field (content), so i've only rendered that form field in my template (pre-populated with the previous post.content
. The other fields are just fields of the object (not a form/can't be edited).
...
<form method="post" action="" enctype="multipart/form-data">{% csrf_token %}
<h1>{{ form_post.title }}</h1>
<p>{{ edit_form.content}}</p>
<p>{{ form_post.category }}</p>
</form>
...
and here is my Post model:
class Post(models.Model):
...
title = models.TextField(max_length=76)
content = models.TextField(null=False, default='')
category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1')
When the edit form is submitted, form_errors
returns this:
<ul class="errorlist">
<li>title<ul class="errorlist"><li>This field is required.</li></ul></li>
<li>category<ul class="errorlist"><li>This field is required.</li></ul</li>
</ul>
Why is this happening? Doesn't:
instance = edit_form.save(commit=False)
instance.save(update_fields=['content'])
keep the fields from the orignal Post and just change the content field?