I'm trying to create a search bar in Django, where users can enter a value to search for, click enter / search button, and then the url redirects to https:localhost:3000/usearch/abc, if they for example search for abc. This is URL paramter can always change based on the search, and it should send the parameter to the views.py file to be processed, though I can't get it to work.
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('register/', views.register, name='register'),
path('usearch/', views.usearch, name='usearch'),
path('usearch/<str:query>', views.usearch_query, name='usearch_query'
]
views.py
def usearch(request):
return render(request, 'myapp/usearch.html')
def usearch_query(request, query):
context = {'query': query}
print(query) # Testing the search result
return render(request, 'myapp/usearch_query.html'}
usearch.html
<form method="GET" action="{% url 'usearch_query' %}
<input type="search" placeholder="Search here...">
<button type="submit"> Search </button>
</form>
usearch_query.html
{{ query }}
I essentially want the user to search something, have it navigate to usearch/<search_parameter> and process the search in the usearch_query function so I can do some computations with it.
Related
I am trying to implement form in django, where I will take input from user, e.g, its table name and then I want to show all the content on the webpage. So, far I tried below code.
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import HttpResponse
from .models import my_custom_sql
from django.core.exceptions import *
def index(request):
return render(request, 'forms_spy/form.html')
def search(request):
if request.method == 'POST':
search_id = request.POST.get('textfield', None)
try:
webpages_list = my_custom_sql.objects.get(name = search_id)
data_list = {'access_record':webpages_list}
return render(request,'forms_spy/index.html', context=data_list)
except my_custom_sql.DoesNotExist:
return HttpResponse("no such user")
else:
return render(request, 'forms_spy/form.html')
forms_spy/models.py
from django.db import models
# Create your models here.
def my_custom_sql(TABLE):
with connections["my_oracle"].cursor() as cursor:
cursor.execute("SELECT * FROM {};".format(TABLE))
row = cursor.fetchall()
return row
templates/forms_spy/form.html
<form method="POST" action="/search">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
urls.py under project folder:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from forms_spy.views import *
urlpatterns = [
# url(r'^$', views.index, name='index'),
#url(r'^', include('livefleet.urls', namespace='livefleet')),
path('admin/', admin.site.urls),
url(r'^search/', search),
url(r'^index/', index),
]
I referred to this link. When I entered the value getting below error.
RuntimeError at /search
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/search/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
change in urls.py
from
url(r'^search/', search),
to
url(r'^search/', search, name='search'),
<form method="POST" action="{% url 'search' %}">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
ur url is search/ , so u need to put the same in the form action
change urls to
path('search/', search)
slash character for dynamic route, example call in browser (http://domain/search) or (http://domain/search/) if you using both it's work.
templates
<form method="POST" action="/search/">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>
I've been trying to create a movie survey in Django for an assignment, and I am currently working on the function. I can't seem to understand why won't it recognize the URL I pass.
I tried removing the hardcoded URL as shown in the Django tutorial on the framework's site, but that doesn't make the error go away.
Here's an excerpt from urls.py:
urlpatterns = [
url(r'^$', views.index, name="index"),
path('movie=<int:movie_id>&user=<int:user_id>/', views.movie, name='movie'),
path('ratings/', views.ratings, name='movie'),
path('rating/<int:movie_id>/', views.rating, name='movie'),
path('movie=<int:movie_id>&user=<int:user_id>/vote/', views.vote, name='vote'),
path('register/',views.register, name='register'),
]
This is my movie view( supposed to present a movie and a star rating radio for the user to rate the movie), where the URL is constructed and passed to HTML:
def movie(request,movie_id,user_id):
movie = get_object_or_404(Movie, pk=movie_id)
voteURL = '/polls/movie=' + str(movie_id) + '&user='+str(user_id)+'/vote/'
context = {
'mymoviecaption':movie.Title,
'moviePoster': 'https://image.tmdb.org/t/p/original'+tmdb.Movies(movie.TMDBID).images().get('posters')[0].get('file_path'),
'myrange': range(10,0,-1),
'myuserid':user_id,
'voteurl': voteURL,
'mymovieid':movie_id
}
#print(nextURL)
translation.activate('en')
return HttpResponse(render(request, 'movieview.html', context=context))
The HTML excerpt, where the vote view is called:
<form action="{% url voteurl %}" method="post">
{% for i in myrange %}
<input id="star-{{i}}" type="radio" name="rating" value={{i}}>
<label for="star-{{i}}" title="{{i}} stars">
<i class="active fa fa-star" aria-hidden="true"></i>
</label>
{% endfor %}
<input type="submit">Vote!</input>
</form>
The vote view( should save to database and redirect to the next movie, doesn't save to database yet, because I didn't want to clutter it with records until I am sure I got the function to work):
def vote(request, movie_id,user_id):
try:
nextmovie=get_object_or_404(Movie, pk=movie_id+1)
nextURL = '/polls/movie=' + str(movie_id + 1) + '&user='+str(user_id)+'/'
except Http404:
nextURL = '/polls/ratings'
try:
myrating = int(request.POST['rating'])
print(myrating)
except:
# Redisplay the question voting form.
return render(request, '/polls/movie=' + str(movie_id + 1) + '&user='+str(user_id)+'/', {
'error_message': "You didn't select a choice.",
})
return HttpResponseRedirect(nextURL)
No matter what I try, I get the NoReverseMatch at /polls/movie=1&user=9/ whenever I try to load the first movie page, despite said URL being defined in urlpatterns.
This is not the way how you provide two pk in the urls
It should be like this
path('movie/<int:movie_id>/<int:user_id>/', views.movie, name='movie'),
Also this is not the way of providing url in the template so it should be something like this
<form action="{% url 'vote' %}" method="post">
# {% url 'url_name' %}
# if app_name provided {% url 'app_name:url_name' %}
And please follow the tutorials step by step
I have a login form with POST method and when I submit the login data, it goes straight to the empty url and doesn't execute the login method in views.py. Ideally, after I submit the form in www.url.com/login via submit button, it should return a HttpResponse but instead, it takes me to www.url.com/
I am new to Django, I'd appreciate it if you could look into it. Thanks!
home.html
<center><h1>Welcome to my website</h1>
<form method='POST'> {% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
</center>
urls.py
from django.contrib import admin
from django.urls import path
from .views import home, login
urlpatterns = [
path('', home),
path('login/', login),
path('admin/', admin.site.urls),
]
forms.py
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control", "placeholder":"Your username"}))
password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control", "placeholder":"Your password"}))
views.py
from django.contrib.auth import authenticate, login
from django.http import HttpResponse
from django.shortcuts import render
from .forms import LoginForm
def home(request):
context={
"form": "Test"
}
return render(request, "home.html", context)
def login(request):
login_form = LoginForm(request.POST or None)
context={
"form": login_form
}
if login_form.is_valid():
username = login_form.cleaned_data.get('username')
password = login_form.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
#request.user.is_authenticated()
login(request, user)
return HttpResponse("You are now logged in")
else:
return HttpResponse('Error')
return render(request, "home.html", context)
First, you should set an attribute action in the form which set a url to send.
Second, a url value in action must be clear. It's not a matter of Django but HTML.
I'd like to recommend you to use absolute path. If you use relative path, a slash string would be added whenever you send a request.
<form action="/login/" method='POST'>
{% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
This is because your form doesn't contain action, i.e. where should the POST call be made with the user credentials.
Try following change in home.html:
<center><h1>Welcome to my website</h1>
<form action="" method='POST'> {% csrf_token %}
{{ form }}
<button type='submit' class='btn btn-default'>Submit</button>
</form>
</center>
Following the answers before, it would be a good practice to use named patterns instead of fixed urls.
# urls
...
path('login/', login, name='login'),
...
# template
<form action="{% url 'login' %}" method='POST'>
So if you change for example
login/
for
accounts/login/
You don't have to change the template as well.
urlpatterns = [
re_path('^$', home_page),
re_path('^admin/', admin.site.urls),
re_path('^register/$', register_page, name='register'),
re_path('^login/$', login_page, name='login'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I solved this by adding ^$to the beginning and end of the patterns.
I have just started on Django and am quite new to the whole thing.
I went through the whole tutorial on
https://docs.djangoproject.com/en/1.7/intro/tutorial03/ , which involves settings up the database and writing a simple form.
To start off my journey in Django, I plan to write a simple app that runs on localhost. And I have faced a issue in passing inputs form a form.
I have created a Name class in the models.py with 1 attribute
#name of the person
value = models.CharField(max_length=50)
In my index link: http://localhost:8000/helloworld/, it contains a simple 1-input-field form as follows:
<form method="post" action="{% url 'helloworld:hello' %}">
{% csrf_token %}
Enter Name: <input size="80" name="link" type="text">
<button type="submit">Submit</button>
</form>
The aim of the form is to return the input data to the same link (http://localhost:8000/helloworld/) with a input message of:
"Welcome [NAME], Hello World"
In my views.py, the following method is written:
def hello(request,name):
p = get_object_or_404(Link, pk=name)
try:
input_link = p.choice_set.get(pk=request.POST['link'])
except (KeyError, Link.DoesNotExist):
return render(request, 'helloworld/index.html',{
'error_message': "You did not enter a name",
})
else:
return HttpResponseRedirect(reverse('helloworld:index', args=(p.value)))
How ever if I access the page http://localhost:8000/helloworld/, and entered a data in the field and click submit, it brings me to the page
Page not found (404)
Request Method: POST
Request URL: http://localhost:8000/helloworld/url%20'helloworld:hello'
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^helloworld/ ^$ [name='index']
^helloworld/ ^(?P<pk>\d+)/$ [name='detail']
^helloworld/ ^(?P<pk>\d+)/results/$ [name='results']
^helloworld/ ^(?P<question_id>\d+)/vote/$ [name='vote']
^admin/
The current URL, helloworld/url 'helloworld:hello', didn't match any of these.
The content in the urls.py was from https://docs.djangoproject.com/en/1.7/intro/tutorial04/#amend-urlconf
As requested, the content of urls.py:
from django.conf.urls import patterns, url
from domparser import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
May I know how do I go about solving this issue?
Thanks!
Simply an answer for this type. If you want to post to same url you are currently now.Try this and chenge def hello(request, name) to def hello(request).
action=""
Otherwise if urls.py
urlpatterns = patterns('app.views',
url(r'^$', view="index", name="app_index"),
)
Try this
action="{% url app_index %}"
As i found, in yours you can apply
action="{% url helloworld:index %}"
Hope this helps
For your answer updated. Try this
<form method="post" action="{% url "index" %}">
You need change this line
<form method="post" action="{% url 'helloworld:hello' %}">
to
<form method="post" action="{% 'helloworld:hello' %}">
So I'm trying to get something very simple accomplished. I want to enter a term into my search box, and display it on the resulting page.
My HTML for the form is
<form method="get" action="/results/" class="navbar-form pull-right">
<input type="text" id="searchBox" class="input-medium search-query" name="q" placeholder="Search">
<input type="submit" class="btn" value="Search" >
</form>
The views.py looks like this:
def search(request):
query = request.GET['q']
t = loader.get_template('template/results.html')
c = Context({ 'query': query,})
return HttpResponse(t.render(c))
And finally the result template contains:
<div>You searched for: {{ query }} </div>
Here's the urls.py
urlpatterns = patterns('',
url(r'^home/$', 'search.views.home'),
url(r'^results/$', 'search.views.results'),
Nothing is showing up in the {{ query }} space.
Ok so the action handling the search in your views.py is supposed to be search but as I suspected in your urls.py you don't call the search method anywhere.
Where do you execute search method?
Urls should be like this:
urlpatterns = patterns('',
url(r'^home/$', 'search.views.home'),
url(r'^results/$', 'search.views.search'),
# or at least have a url for the search view
Note the action attribute in your form
It is action="/results/". This means result view is the one who is supposed to be handling the form. You may also change this to action="/search/" and have your urls like this:
urlpatterns = patterns('',
url(r'^home/$', 'search.views.home'),
url(r'^results/$', 'search.views.results'),
url(r'^search/$', 'search.views.search'),