我正在尝试扩展我的小项目的搜索功能。现在我可以使用char字段进行搜索,但我想添加一些复选框。一些项目已被标记为SRED复选框,我希望能够搜索仅SRED项目。
这是我目前的搜索设置。
models.py
class Project(models.Model):
...
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
pre_quote = models.CharField(max_length=3)
quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True)
...
SRED = models.BooleanField()
...
Views.py
@login_required
def search(request):
if request.method == 'POST':
form = SearchProjectForm(request.POST)
if not form.is_valid():
return render_to_response('project/search.html', {'form': form}, context_instance=RequestContext(request))
else:
projects = Project.objects.filter(proj_name__icontains = form.cleaned_data["text"])
companies = Clients.objects.filter(client_name__icontains = form.cleaned_data["text"])
return render_to_response('project/search.html', {'form': form, 'projects':projects, 'companies': companies}, context_instance=RequestContext(request))
form = SearchProjectForm()
return render_to_response('project/search.html', {'form': form}, context_instance=RequestContext(request))
forms.py
class SearchProjectForm(forms.Form):
text = forms.CharField(label = "Search")
search.html
<form method="POST" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Search"/>
</form>
<h3>Search Results</h3>
...
非常感谢任何帮助!
再次感谢
史蒂夫
答案 0 :(得分:1)
您需要将项目传递给Form构造函数,然后根据需要添加框字段:
form = SearchProjectForm(project, request.POST)
和
class SearchProjectForm(forms.Form):
text = forms.CharField(label = "Search")
def __init__(self, project, *args, **kwargs):
form = forms.Form.__init__(self, *args, **kwargs)
if project.has_additional_fields():
self.fields['additional_field'] = forms.SomeField()
if project.only_additional_fields():
self.fields['text'].required = False