2017-04-23 74 views
0

我有:蟒滤波器无值

1. models.py

class Post(models.Model): 
    ROOT_CHOICES = (
     ('Manufacturing', 'Manufacturing'), 
     ('Transportation', 'Transportation'), 
     ('Installation', 'Installation'), 
     ('Operation', 'Operation'), 
    ) 
    root1 = models.CharField(max_length=250, choices=ROOT_CHOICES, default='Manufacturing') 
    root2 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) 
    root3 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) 
    root4 = models.CharField(max_length=250, choices=ROOT_CHOICES, null=True, blank=True) 

2. views.py

def post_detail(request, slug): 
    post=get_object_or_404(Post, slug=slug) 
    if request.method == "POST": 
     form = CommentForm(request.POST) 
     if form.is_valid(): 
      comment = form.save(commit=False) 
      comment.post=post 
      comment.save() 
      return redirect('data:post_detail', slug=post.slug) 
    else: 
     form=CommentForm() 
    template = 'data/post_detail.html' 
    context = {'form':form,'post':post} 
    return render(request, template, context) 

3. HTML

<div class="col-sm-3"> 
    <div class="post-parameters"> 
     <p class="text-parameters"> Root: {{ post.root1 }}, {{ post.root2 }}, {{ post.root3 }}, {{ post.root4 }}</p> 
    </div> 
</div> 

看起来像这样,现在,在我的html文件中:Root:Manufacturing,None,None,None这是正确的。不过,我不想显示(如果有的话)无值,例如根:制造

回答

1

可以使用default_if_none过滤器,因此:{{post.root1|default_if_none:""}}

或者,你可以检查每一个值特别

{% if post.root1 %} {{post.root1}} {% endif %} 
+0

它的作品!谢谢 – George