I want to write a view function to edit a blog post. And I’m wondering how to tell Django what object to modify in the database using instance parameter without prefilling of a form.
BlogPost model
<code>class BlogPost(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.title[:50]
</code>
<code>class BlogPost(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.title[:50]
</code>
class BlogPost(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.title[:50]
Form model
<code>class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ["title", "text"]
labels = {"title": "", "text": ""}
</code>
<code>class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ["title", "text"]
labels = {"title": "", "text": ""}
</code>
class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ["title", "text"]
labels = {"title": "", "text": ""}
The view function
<code>def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
if request.method != "POST":
form = BlogPostForm(instance=post)
else:
form = BlogPostForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
</code>
<code>def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
if request.method != "POST":
form = BlogPostForm(instance=post)
else:
form = BlogPostForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
</code>
def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
if request.method != "POST":
form = BlogPostForm(instance=post)
else:
form = BlogPostForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
As far as I understood it, the instance parameter tells Django what object to modify in the database using form.save() method.
But how to do it without prefilling of the form?