B
B
blazer052016-03-22 14:55:30
Django
blazer05, 2016-03-22 14:55:30

How to make the publication of news by means of a checkbox?

When creating news, it is necessary to make it published or removed from publication. I basically did half, added to the model

published = models.BooleanField(verbose_name='Опубликован')

In the admin panel I displayed in list_display = ['published'], but I don't know how to write a handler?
Now the news is all displayed even if the news is removed from publication. Tell me how to write a view?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oscar Django, 2016-03-22
@blazer05

class NewsView(ListView):
  model = News
  def get_queryset(self):
    return super().get_queryset().filter(published=True)

What's the problem then?

A
Artyom Bryukhanov, 2016-03-31
@drupa

#models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from .managers import NewsQuerySet

class Product(models.Model):
    is_published = models.BooleanField(
        default=False,
        verbose_name=u'Показывать на сайте',
    )
    title = models.CharField(
        max_length=200,
        verbose_name=u'Название',
    )

    objects = NewsQuerySet.as_manager()
    
    class Meta:
        verbose_name = u'Новость'
        verbose_name_plural = u'Новости'

    def __unicode__(self):
        return self.title

I usually do this. I create a manager, it contains a filter for publication.
#managers.py
# -*- coding: utf-8 -*-
from django.db import models

class NewsQuerySet(models.QuerySet):
    def published(self):
        return self.filter(is_published=True)

I call it like this
#views.py
# -*- coding: utf-8 -*-
from django.views.generic import ListView, DetailView

from .models import News


class NewsList(ListView):
    queryset = News.objects.published()


class NewsDetail(DetailView):
    queryset = News.objects.published()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question