我试图让我的搜索在Django中查询我的数据库。
form.is_valid()中的行是我添加到我的网站添加数据的其他形式,它完美无缺。 唯一的问题是查询事物.. 我只是不明白为什么在点击搜索后我仍然会看到所有帖子而不是我搜索的帖子..
views.py -
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
args = {'form' : form, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
query = request.GET.get("q")
if query:
posts = serverlist.filter(Project__icontains=query)
if form.is_valid(): # Checks if validation passed
post = form.save(commit=False)
post.save()
text = form.cleaned_data['ServerName']
form = HomeForm()
return redirect('serverlist')
args = {'form': form, 'text': text}
return render(request, self.template_name,args)
index.html -
<div class="container">
<br>
<center><h1>DevOps Server List</h1></center>
<br>
<form method='GET' action=''>
<input type='text' name='q' placeholder='Search Item'/>
<input type='submit' value='Search' />
</form>
<table class="table table-hover">
<thread>
<tr>
<th> Server Name </th>
<th> Owner </th>
<th> Project </th>
<th> Description </th>
<th> IP Address </th>
<th> ILO </th>
<th> Rack </th>
<th> Status </th>
<th> </th>
</tr>
</thread>
<tbody>
{% for server in posts %}
<tr>
<div class ="server">
<td>{{ server.ServerName }}</td>
<td>{{ server.Owner }}</td>
<td>{{ server.Project }}</td>
<td>{{ server.Description }}</td>
<td>{{ server.IP }}</td>
<td>{{ server.ILO }}</td>
<td>{{ server.Rack }}</td>
<td>{{ server.Status }}</td>
<td>
forms.py -
class HomeForm(forms.ModelForm):
ServerName = forms.CharField(widget=forms.TextInput,max_length = 30)
Owner = forms.CharField(max_length = 50)
Project = forms.CharField(max_length = 30)
Description = forms.CharField(max_length = 255)
IP = forms.CharField(max_length = 30)
ILO = forms.CharField(max_length = 30)
Rack = forms.CharField(max_length = 30)
Status = forms.CharField(max_length = 30)
class Meta:
model = serverlist
fields = ('ServerName' ,'Owner','Project','Description','IP','ILO','Rack','Status',)
答案 0 :(得分:1)
您应该在get方法中添加过滤器:
posts = serverlist.objects.all()
query = request.GET.get("q")
if query:
posts = serverlist.objects.filter(Project__icontains=query)
# ^^^^^^^^^^^^^^^^^^^^^^^
答案 1 :(得分:0)
您正在使用post方法执行搜索。因此,您需要使用POST方法发送数据。请更改表单标记中的方法,如下所示。
<form method='POST' action=''>
{% csrf_token %}
<input type='text' name='q' placeholder='Search Item'/>
<input type='submit' value='Search' />
</form>
当你使用POST方法时,你也需要csrf。
{% csrf_token %}
模板标记用于此目的。
顺便说一下,您正在使用表单对象来验证表单。但是您在模板中手动创建了表单。您也应该使用它来创建HTML。因此,您的模板将如下所示:
<form method='POST' action=''>
{% csrf_token %}
{{ form }}
<input type='submit' value='Search' />
</form>
这可以解决您的表格无效问题。由于你没有分享你的HomeForm来源,我无法分辨。