-1

I'm trying to apply an activate/deactivate feature for my posts on a blog app. Here is my model. My desire is to be able to activate the post to show it in a template but how can I change (set) the value of is_activate field through the view.py? Here is my model:

class Post(models.Model):
   title = models.CharField(max_length=250)
   slug = models.SlugField(max_length=250)
   body = models.TextField()
   is_activate = models.BooleanField(default=False)

Summarizing: I need a button which on clicking activates a post and then show it in a template with other activated posts.

Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
Italo Lemos
  • 972
  • 1
  • 9
  • 20

3 Answers3

2

You can access the post by primary key

post = Post.objects.get(id=id)
post.is_activate = True
post.save()

by this code your is_activate flag will be set for this post

SHIVAM JINDAL
  • 2,844
  • 1
  • 17
  • 34
1

Try this: This is your model.py

class Post(models.Model):
   title = models.CharField(max_length=250)
   slug = models.SlugField(max_length=250)
   body = models.TextField()
   is_activate = models.BooleanField(default=False)

and view.py

from foldername import Post //if there are subfolders use'.' between them.
//import the other packages which u need
form=form_name  //your form name
template=template_name  //your template name
def post( self, request, *args, **kwargs ):
        try:
            form = self.form_class( request.POST)
            if form.is_valid():
            new_formfile = form.save(commit=False)
            new_formfile.is_activate = true
            new_formfile.save()
        except Exception as e:
            return render(request, 'exception.html', {'exception': str(e), 'message': e.message})

OR

//another method write in try block

id = request.GET.get('id')
id_instance = Post.objects.get( pk = id )
form = self.form_class(request.POST, instance = id_instance)
if form.is_valid():
new_formfile = form.save(commit=False)
new_formfile.is_activate = true
new_formfile.save()
form.save()
bob marti
  • 1,523
  • 3
  • 11
  • 27
0

With "update()", you can update "is_activate" field as shown below:

Post.objects.filter(id=id).update(is_activate=True)
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129