简体   繁体   中英

How do I change a value of a BooleanField in Django?

The view class:

class PostCreateView(CreateView):
    form_class = PostForm
    model = Post

The model class:

class Post(models.Model):
    title = models.CharField(max_length=256)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    neg_sentiment = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('post_detail', kwargs={'pk': self.pk})

    def __str__(self):
        return self.title

I'm trying to get BooleanField to change to True, but I don't know how to reassign it

urls.py:

urlpatterns = [
    path('publish_post/<int:pk>', views.PublishPost, name='publish_post'),
]

views.py:

def PublishPost(request, pk):

    post = Post.objects.get(pk=pk)
    post.neg_sentiment.save()
    post.save()

    context = {'success' : True}

    return HttpResponse(context)

Then in your template you can set up a post request to 'publish_post' with the id of the post object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM