I am looking at trying to expand my search function for my small project. Right now I have the ability to search using a char field but I want to add a few checkboxes. Some projects have been flagged with the SRED checkbox and I want to be able to also search for SRED only projects.
Here is my current search setup.
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):
t开发者_如何学Pythonext = forms.CharField(label = "Search")
search.html
<form method="POST" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Search"/>
</form>
<h3>Search Results</h3>
...
Any help would be greatly appreciated!
Thanks again
Steve
You need to pass project to Form constructor and then add box fields if necessary:
form = SearchProjectForm(project, request.POST)
and:
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
More here: http://jacobian.org/writing/dynamic-form-generation/
精彩评论