Reputation: 99
This particular Boolean field determines whether a post is a draft. The default is set to True.
When the user edits a draft, I want the value to be automatically changed to False, so that it is listed with all the other posts (instead of in the drafts list).
Could the submit button both submit the post and change the Boolean value? Ideally, I suppose, the field would be changed as soon as the draft form is entered.
Here is the relevant code: Template for editing Draft
{{ title }}</B></h3></div>
<div class="row">
<div class="col-sm-12-md-7 col-sm-offset-0 col-sm-8">
<div class="panel panel default">
<div class="panel-body">
<p class="well col-sm-offset-3 col-sm-12">{{ summary }}</p>
<form class="form-horizontal" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{% include 'posts/form-template.html' %}
<div class="form-group col-sm-offset-3 col-sm-6">
<div class="col-sm-offset-9 col-sm-10">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
This my form for editing the draft
class UpdateForm(forms.ModelForm):
class Meta:
model = Post
fields = [
"title", "content", "categories", "tags",
]
This is the Post model
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=100)
content = HTMLField()
draft = models.BooleanField(default=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
upvote = VotableManager()
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
categories = models.ManyToManyField(
'category.Category',
help_text='Categorize this item.'
)
tags = models.ManyToManyField(
'category.Tag',
help_text='Tag this item.'
)
suggest = models.ForeignKey('Suggest', blank=True, null=True, default=0)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
Here is the view for editing the draft
def post_update(request, id=None):
instance = get_object_or_404(Post, id=id)
model = Post
form = UpdateForm(request.POST or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
context = {
"title": instance.title,
"instance": instance,
"form": form,
"summary": instance.summary,
}
return render(request, "posts/suggest_form_update.html", context)
Upvotes: 1
Views: 1511
Reputation: 4495
You could accomplish this in two ways:
if form.is_valid():
conditional, before the object is saved.In your form by customising the save()
method.
def save(self, *args, **kwargs):
self.instance.draft = True
return super(UpdateForm, self).save(*args, **kwargs)
Upvotes: 1