I am very new to Django and I am creating a very simple project. However, the "search" part of my project is having some issues. Every time I try to search, it redirect me to the search template but not showing the data from the database. No error message. Here's my code...
models.py
class Userprofile(models.Model):
use_id = models.IntegerField()
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
position = models.CharField(max_length = 50)
email = models.CharField(max_length= 100)
password = models.CharField(max_length= 100)
def __str__(self):
return self.first_name
account_list.html This is the template where the search bar is located
<div >
<form method="post" action="{% url 'account_search' %}" autocomplete="off">
<br>
{% csrf_token %}
<input type="text" name="acc_search" placeholder="Search Account">
<input type="submit" name="submit" value="Search" style="width: 24%"></p>
</form>
</div>
<hr>
views.py
def account_search(request):
if request.method == "POST":
account_search = request.POST.get('acc_search')
accounts = Userprofile.objects.filter(use_id__contains=account_search) | Userprofile.objects.filter(first_name__contains=account_search) | Userprofile.objects.filter(last_name__contains=account_search) | Userprofile.objects.filter(position__contains=account_search) | Userprofile.objects.filter(email__contains=account_search)
return render(request, 'core/account_search.html', {'account_search': account_search, 'accounts':accounts})
else:
return render(request, 'core/account_search.html', {})
account_search.html `
{% if account_search %}
<div >
<div >
<h1>'{{ account_search }}' in Accounts</h1>
</div>
<table rules="all" style="border: 1px">
<thead>
<td>Personnel's ID</td>
<td>Name</td>
<td>Position</td>
<td>Email</td>
<td>Action</td>
</thead>
<tbody>
{% for userprofile in userprofiles %}
<tr>
<td>{{ userprofile.use_id }}</td>
<td>{{ userprofile.first_name }}
{{ userprofile.last_name }}</td>
<td>{{ userprofile.position }}</td>
<td>{{ userprofile.email }}</td>
<td >
<a href="account_edit/{{ userprofile.id }}" >Edit</a>
<a href="account_delete/{{ userprofile.id }}" >Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<h1 >You forgot to enter the text in the input box.</h1>
{% endif %}
I've searched in the Google and tried but I can't find any solution or any discussion on how I can fix it.
I hope someone can help me, thank you. And I'm sorry for my bad English.
CodePudding user response:
You are passing accounts
as context variable from the view, but in template, you are looping through userprofiles
. Hence change this line in template:
{% for userprofile in userprofiles %}
to
{% for userprofile in accounts %}
CodePudding user response:
You are passing accounts as "accounts" in the view, but looking for "userprofiles" in the template. You have to use "accounts" in the template as well.
{% for userprofile in accounts %}