2017-05-04 61 views
0

我是新的python/Django,我有一个问题,我试图使用复选框过滤在我的HTML表中,我真的不知道该怎么做。Python - Django过滤

This is what i have now

I want to add these

models.py

class Tags(models.Model): 
    tag_frequency = models.CharField(max_length=250) 

views.py

@login_required(login_url='/login/') 
def index(request): 
    title = 'Tags' 
    all_tags = Tags.objects.all() 
    return render(request, 'tag/index.html' ,{'all_tags':all_tags, 'title':title}) 

如何使用过滤器,这些,我想这样的事情,但没有按” t工作:

LF = 125 - 134.2 KHz 
HF = 13.56 MHz 
UHF = 860 - 960 MHz 

LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2) 
+0

你是什么意思由'不工作'?该过滤器查询的返回值是什么? – alix

+0

更像是我不知道如何使它在模板中工作.. – Demina

+1

'Tag.frequency'是一个'CharField',所以你不能期望过滤浮动值显然。首先得到一个工作模型,然后是时候担心“如何使它在模板中工作” –

回答

0

为了使您的查询工作,你有你的字段更改为FloatField

class Tags(models.Model): 
    tag_frequency = models.FloatField(default=0.00, null=True, blank=True) 

nullblankdefault值根据您的需求。

然后,把你的复选框(或无线输入)在你的HTML表单是这样的:

<form action="" method="post"> 
    <!-- other form fields and csrf_token here --> 
    <div><label for="input_lf"><input type="checkbox" name="is_lf" id="input_lf"> LF</label></div> 
    <div><label for="input_hf"><input type="checkbox" name="is_hf" id="input_hf"> HF</label></div> 
    <div><label for="input_uhf"><input type="checkbox" name="is_uhf" id="input_uhf"> UHF</label></div> 
    <input type="submit" value="Submit"/> 
</form> 

那么在你看来,你可以尝试这样的事:

def form_view(request): 
    if request.method == 'POST': 
     # these strings come from HTML Elements' name attributes 
     is_lf = request.POST.get('is_lf', None) 
     is_hf = request.POST.get('is_hf', None) 
     is_uhf = request.POST.get('is_uhf', None) 

     # Now make your queries according to the request data 
     if is_lf: 
      LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2) 

     if is_hf: 
      # another query here 

     # and rest of your view