Searching database table through get method in django

Viewed 230

I am new to django and having trouble to get result from my models database table through 'GET' method.

my model is:

class records(models.Model):
    sex = (('M', 'MALE'),('F', 'FEMALE'),)
    reg_number = models.CharField(max_length=15)
    mic_number = models.CharField(max_length=15)
    dog_name = models.CharField(max_length=20)
    dog_breed = models.CharField(max_length=50)
    color = models.CharField(max_length=20)
    dog_Sex = models.CharField(max_length=1,choices=sex)
    Breeder = models.CharField(max_length=30)
    Owner_name = models.CharField(max_length=50)
    address = models.TextField(max_length=264)

my views is:

from django.shortcuts import render
import datetime
from .forms import RecordForm
from .models import records

# Create your views here.
def index (request):
    return render(request, "newyear/index.html")

def search (request):
    mic = request.GET['mic']
    r = records.objects.filter(mic_number__iexact = mic )
    return render(request,"newyear/search.html", {"records": r})

my index template is:

<form action="{% url 'search'%}" enctype="application/x-www-form-urlencoded" method="GET">
    <ul><input type="text" name = "mic"></ul>
  <button type="submit" name= "search">search</button>
</form>

my search template is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
  <h1>THIS IS RESULT PAGE</h1>
  {% if records %}
  <table>
    {% for records in records %}
    <tr>
      <td>{{records.color}}</td>
      <td>{{records.dog_name}}</td>
      <td>{{records.mic_number}}</td>
    </tr>
  {% endfor %}
  </table>
  {% endif %}
</body>
</html>

search.html only displays "THIS IS RESULT PAGE". what is wrong in above approach please help. I am struggling from 3 days on it.

1 Answers

The looping variable(records) is same as looped details(records).So please change records to record like this. And Change GET method to POST.

<h1>THIS IS RESULT PAGE</h1>
  {% if records %}
  <table>
    {% for record in records %}
    <tr>
      <td>{{record.color}}</td>
      <td>{{record.dog_name}}</td>
      <td>{{record.mic_number}}</td>
    </tr>
  {% endfor %}
  </table>
  {% endif %}

views.py

def search (request):
    mic = request.POST['mic']
    r = records.objects.filter(mic_number__iexact = mic )
    return render(request,"newyear/search.html", {"records": r})

index.html

<form action="{% url 'search'%}" enctype="application/x-www-form-urlencoded" method="POST">
    <ul><input type="text" name = "mic"></ul>
  <input type="submit" value="search" name= "search">
</form>
Related