Django search functionality :-
open command prompt in windows
then type go to d: drive
D:\> mkdir myap
D:\myap>cd myap
D:\myap>python -m venv env
D:\myap>env\Scripts\activate
D:myap>pip install django
D:\myap>django-admin startproject myproject
D:\myap>cd myproejct
D:\myap\myproejct>python manage.py startapp hello
D:\mywork\myproejct>python manage.py runserver.
Step 1:-
Write code for models.py file under your app folder
from django.db import models
# Create your models here.
class ContactForm(models.Model):
fullname= models.CharField(max_length=100)
email= models.EmailField()
contact= models.CharField(max_length=50)
message= models.CharField(max_length=200)
write code for admin.py file in your app folder :-
from django.contrib import admin
from .models import ContactForm
# Register your models here.
admin.site.register(ContactForm)
Then run command py manage.py makemigrations and py manage.py migrate
Step 2:-
Step 1:- write code for search1.html file in your templates folder :-
<form name="myform" method="GET" action="{% url 'search1' %}">
<input type="text" name="q" placeholder="Search" />
<button type=submit> search</button></form>
{% for data in data %}
<td>{{data.fullname}}</td>
<td>{{data.email}}</td>
<td>{{data.contact}}</td>
{% endfor %}
Step 3:- urls.py in your app folder.
from django.urls import path
from .import views
urlpatterns=[
path('',views.index,name='index'),
path('search1/', views.search1,name='search1'),
]
Step 4:- write views.py file code under your app folder :-
from urllib import request
from django.shortcuts import render
from hello.models import ContactForm
from hello.forms import FormContactForm
from django.http import HttpResponse
def index(request):
return render(request, "home.html")
def search1(request):
if 'q' in request.GET:
q=request.GET['q']
data=ContactForm.objects.filter(fullname=q)
else:
data =ContactForm.objects.all()
return render(request,'search1.html',{
'data':data
})
Sign up here with your email
ConversionConversion EmoticonEmoticon