Google Search using python - python

I get data from input. When I click to search button I need to open webbrowser page and see my input data in google. How can I do that? Many thanks.
This is my code:
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'index.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
return HttpResponse(search_query)
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")
for j in search(search_query, tld="co.in", num=10, stop=1, pause=2):
print(j)
else:
return HttpResponse('Invalid input.')
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
urls.py
from django.urls import path
from firstapp import views
urlpatterns = [
path('', views.index, name='home')
]
All files are in hello folder. My app namely firstapp path: C:\Users\user\Desktop\hello\firstapp
index.html path is:
C:\Users\user\Desktop\hello\firstapp\templates

In order to redirect to google you need to have your search textfield to use a parameter called q. Here is an index.html file that would work:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="https://google.com" method="GET">
{% csrf_token %}
<input type="text" name="q" placeholder="some text"><br>
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>

Related

Django stops updating data to mysql after page refresh

I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?
Stuff for reference:
views.py
from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages
def insertToDB(request):
if request.method == "POST":
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert()
post.uname = request.POST.get('uname')
post.email = request.POST.get('email')
post.message = request.POST.get('message')
post.save()
messages.success(request, "Message sent successfully.")
return render(request, "contact.html")
else:
return render(request, "contact.html")
models.py
from django.db import models
class dbInsert(models.Model):
uname = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
class Meta:
db_table = "contactrequest"
urls.py
"""
websiteDB URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
path('homepage', index.page_home, name= 'hpage'),
path('', views.insertToDB),
path('contactpage', index.contact_page, name= 'cpage')
]
contact.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
<title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">
<script src="{% static 'js/main.js' %}"></script>
<div class="top-nav">
HOME
PRODUCTS
CONTACT
ABOUT
COMMUNITY
</div>
<div class="div-align">
<h2>Contact</h2>
<p>Reach us for questions/concerns through the form below.</p>
</div>
<form class="fontmaker" method="post">
{% csrf_token %}
<label for="Username">Username:</label><br>
<input type="text" id="Username" name="uname" required><br>
<label for="E-mail">E-mail:</label><br>
<input type="text" id="Email" name="email" required>
<label for="Reason" class="margin">Message:</label>
<textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
<input type="submit" value="Submit" class="rounded-corners" id="submitBtn">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</form>
</body>
</html>
There are no errors in terminal, and the button click also properly sends a POST req:
Terminal output
I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.
index.py
from django.http import HttpResponse
from django.shortcuts import render
def page_home(request):
return render(request, 'index.html')
def contact_page(request):
return render(request, 'contact.html')
Thanks in advance.
If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:
urlpatterns = [
# …,
path('', views.insertToDB, name='insertToDB'),
# …
]
and then specify the endpoint in the form:
<form class="fontmaker" method="post" action="{% insertToDB %}">
<!-- … -->
</form>
In case of a successful POST request, you should also redirect, for example with:
from django.shortcuts import redirect
def insertToDB(request):
if request.method == 'POST':
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert.objects.create(
uname = request.POST['uname'],
email = request.POST['email'],
message = request.POST['message']
)
messages.success(request, 'Message sent successfully.')
return redirect('cpage')
return render(request, 'contact.html')
else:
return render(request, 'contact.html')
I would advise to work with Django forms [Django-doc], for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.

Review a form before submitting in django

I am building a registration form. I want the users to review their filled-up forms to confirm their submissions. But in my code the form is submitted twice (overwritten not duplicated). Once when they hit the submit button after filling their form and overwritten after hitting the submit button on the review page. As a result if they close the browser in the review page their page is still submitted, which I don't want to allow.
views.py
from django.shortcuts import render, redirect
from .models import *
from .forms import *
# Create your views here.
def index(request):
form = RegisterForm()
print('hi')
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
z = form.cleaned_data
if (Register.objects.filter(email=z['email']).exists()):
print('already exist')
return redirect('/')
else:
print('xx')
return redirect('preview', pk=z.get('id'))
context = {'form':form}
return render(request, 'event/index.html', context)
def preview(request, pk):
prev = Register.objects.get(id=pk)
if request.method == 'POST':
prev.save()
print('overwrite')
return redirect('/')
print('yy')
context = { 'prev':prev,'id':pk}
return render(request, 'event/preview.html', context)
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Registration</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
<div class="mobile-screen">
<div class="header">
</div>
<div class="logo"></div>
<form id="login-form" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.email}}
<input class="btn btn-sm btn-primary" type="submit" value="Register" name="Register">
</form>
</div>
</body>
</html>
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Register(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=254,null=True)
def __str__(self):
return self.name

Django trying to update a specific item that has an id but then also edit other items if need be

I can't figure out why it won't update/edit an item and then add it back to list with the edits. If someone can help me out thanks! If I find my answer before I get a response I will post it. I posted my views.py, urls.py and the html for the edit page confirm_edit.html just so you can see all of what I am dealing with. thanks for the help!
from django.shortcuts import render, redirect, HttpResponse
from .models import Course
def index(request):
context = {
'course' : Course.objects.all()
}
return render(request, 'chp1/index.html', context)
def create(request):
if request.method == "POST":
Course.objects.create(SLA_TYPE_CD=request.POST['Name'],
SLA_TS=request.POST['description'], ACTUAL_COMPLETION_TS=request.POST['description'],
TICKET_NUM=request.POST['description'], NOTE_TXT=request.POST['description'])
return redirect('/')
def edit(request, id):
course_to_edit = Course.objects.get(id=id)
if request.method == "GET":
return render(request, 'chp1/confirm_edit.html', {'course' : course_to_edit})
def update(request, id):
if request.method == "POST":
course_to_edit.update(SLA_TYPE_CD=request.POST['Name'],
SLA_TS=request.POST['description'], ACTUAL_COMPLETION_TS=request.POST['description'],
TICKET_NUM=request.POST['description'], NOTE_TXT=request.POST['description'])
return redirect('/')
def destroy(request, id):
course_to_delete = Course.objects.get(id=id)
if request.method == "GET":
return render(request, 'chp1/confirm_delete.html', {'course' : course_to_delete})
course_to_delete.delete()
return redirect('/')
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^create$', views.create),
url(r'^(?P<id>\d+)/destroy$', views.destroy),
url(r'^(?P<id>\d+)/edit$', views.edit),
]
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit SLA_VARIANCE_NOTE</title>
<link rel="stylesheet" href="{% static 'chp1/css/styles.css' %}">
</head>
<body>
<div id="addcourse">
<h2>Are you sure you want to edit the following post?</h2>
<form action="/{{ course.id }}/edit" method='post'>
SLA_TYPE_CD: <input type="text" name="Name" value=""> <br>
SLA_TS: <textarea name="description" rows="1" cols="40"></textarea> <br>
ACTUAL_COMPLETION_TS: <textarea name="description" rows="1" cols="40"></textarea> <br>
TICKET_NUM: <textarea name="description" rows="1" cols="40"></textarea> <br>
NOTE_TXT: <textarea name="description" rows="1" cols="40"></textarea><br>
{% csrf_token %}
<button>Back</button>
<input name="edit" type="submit" value="update">
</form>
</div>
</body>
</html>

Not able to redirect to view after login

I am trying to create a redirect when the user logs in. For example when user tries to access a link to create blog post he is prompted to log in , and after he gets logged in he is redirected to the page to create the post. I am extracting the next parameter from the url.
blog.urls
from django.conf.urls import url
from blog import views
urlpatterns=[
url(r'^$',views.index,name="index"),
url(r'^signup/$',views.signup_view,name="signup_view"),
url(r'^login/$',views.login_view,name="login_view"),
url(r'^create-post/$',views.create_blog,name="create_post"),
url(r'^logout/$',views.logout_view,name="logout_view"),
]
blog.views:
def login_view(request):
if request.method == 'POST':
form=LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
user=authenticate(username=username,password=password)
if user is not None:
if user.is_active:
login(request,user)
go_to=request.GET.get('next','/')
print go_to
return HttpResponseRedirect(go_to)
else:
return HttpResponse("Not active")
else:
return HttpResponse("User doesn't exist")
else:
form=LoginForm()
return render(request,'blog/login.html',{'form':form})
and blog/login.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form method="POST" action="/login/">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<button type="submit">Submit</button>
</form>
</body>
</html>
Whenever I login it shows the next parameter as '/' while there is "next=/create-blog/" in the url. Please suggest any solution.
you need:
action="/login/{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}"
If the value of {{ request.GET.next }} includes parameters, e.g. http://example.com/?var1=abc&var2=def, then use URL encoding {{ request.GET.net | urlencode }}.

Submitting data from a form to django view

When I open the html file it displays as expected and when I enter data in the text box and submit, It redirects me to localhost/myapp/output/ but why is the data I enter in the text box not submitted for example like localhost/myapp/output/data_I_submitted
My basic html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>db app</title>
</head>
<body>
{% csrf_token %}
<form action="output/" method="post" name="Input">
Data : <input type="text" name="text">
<input type="submit" value="submit">
</form>
</body>
</html>
In my app.urls file:
urlpatterns = patterns('',
url(r'^$',views.index),
url(r'^output/(?P<text>\w+)/$',views.return_data)
)
Finally the view:
def return_data(request,text):
return HttpResponse('entered text ' + text)
If your goal is only getting the text on the form:
change your view to
def return_data(request):
return HttpResponse('entered text:' + request.POST['text'])
edit your urls
urlpatterns = patterns('',
url(r'^$', views.index),
url(r'^output/$', views.return_data)
)
and your template
<form action="output/" method="post">
{% csrf_token %}
...
</form>
you'd better review data submitting in forms.
with two methods you can submit forms data with your request to the forms action attribute:
GET: like http://www.google.com/?q=keyword+to+search
you can access the "keyword+to+search" by:
request.GET['q']
#or better is:
request.GET.get('q', None)
the text arguement is not passed to url pattern. so not accessible in this way
POST:
in this method the data is not in request url.
so to access the forms data submittin by POST method
try this
request.POST['text'] (
#or better is:
request.POST.get('text', None)
but it is highly recommended to use Django forms instead of direct accessing from request.POST or request.GET
so check this: https://docs.djangoproject.com/en/dev/topics/forms/

Categories

Resources