s.spirit
s.spirit

Reputation: 343

Check boolean field state in views.py

I tried to add simple publish/unpublish functionality for item. I made a boolean field in my model and tried to check true/false state in views.py. And if it false - show 404 page..

But I can't write my view correctly - got invalid syntax error. How can I make it work?

My model:

class Article(models.Model):
    class Meta():
        db_table = 'article'

    title = models.CharField(max_length=200, blank=False, null=False)
    anchor = models.CharField(max_length=200, blank=False, null=False)
    image = models.ImageField(upload_to='items', blank=False, null=False)
    text = RedactorField(blank=False, null=False)
    files = models.FileField(upload_to='files', null=True, blank=True)
    date = models.DateField(blank=True, null=True)
    tags = TaggableManager()
    published = models.BooleanField(default=False)

    def __str__(self):
        return self.anchor

My view:

def article(request, anchor):
    article = Article.objects.get(anchor=anchor)
    if article.published = True:
        args = {}
        args['article'] = Article.objects.get(anchor=anchor)
    else:
        Http404

    return render_to_response('article.html', args, context_instance=RequestContext(request))

Upvotes: 2

Views: 3966

Answers (2)

s.spirit
s.spirit

Reputation: 343

As Brandon pointed, I need to use just if article.published: Also, thx to Krishnan and Gocht to explain the syntax.

def article(request, anchor):
    article = Article.objects.get(anchor=anchor)
    if article.published:
        args = {}
        args['article'] = Article.objects.get(anchor=anchor)
    else:
        Http404

    return render_to_response('article.html', args, context_instance=RequestContext(request))

Upvotes: 0

krishnan
krishnan

Reputation: 313

This is actually a common programming error.See Operators

= is actually the assignment operator,whereas == check equality.

The statement you have used returns true all the time and hence pass the If condition.

Also as Brandon pointed out you could always use if article.published for boolean values.

Please mark your question as answered ,If you feel you have solved it.

Upvotes: 2

Related Questions