我正在嘗試爲我的django項目創建一個搜索欄,但每當搜索到某個東西時,它都會返回默認情況下的所有內容。在django中發出搜索請求
下面是從內部views.py代碼:
def index(request):
if not request.user.is_authenticated():
return render(request, 'Lfm/login.html')
else:
lfm = Lfm.objects.filter(user=request.user)
query = request.GET.get('q')
if query:
Lfm = lfm.filter(
Q(name__icontains=query) |
Q(region__icontains=query) |
Q(rank__icontains=query)
).distinct()
return render(request, 'Lfm/index.html', {'lfm': Lfm,})
else:
return render(request, 'Lfm/index.html', {'Lfm': lfm })
models.py文件:
class Lfm(models.Model):
name = models.CharField(max_length=20)
rank = models.CharField(max_length=20, choices=RANKS)
rank_sr = models.IntegerField()
region = models.CharField(max_length=20, choices=REGIONS)
roles = models.CharField(max_length=30, choices=ROLES)
btag = models.CharField(max_length=30)
time = models.CharField(max_length=14, choices=TIMES)
logo = models.FileField()
contact_email = models.EmailField()
和base.html文件
<form class="navbar-form navbar-left" role="search" method="get" action="{% url 'Lfm:index' %}">
<div class="form-group">
<input type="text" class="form-control" name="q" value="{{ request.GET.q }}">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>