space in url Django - python

I am creating a search bar on my site, everything is fine if I pass the names without spaces, being that I pass the word of the search bar directly in the url, as you can imagine the problem arises when the user enters words with space. I also convert the url into utf-8, but I think django does it automatically because even without the conversion in the url if you pass the space it appears at its post% 20, I wanted to clarify that the problem persists if you enter characters like:! ?can someone help me? Thanks in advance.
urls.py:
from django.urls import path
from dac import views
from django.conf.urls.static import static
from django.conf import settings
from django.urls import re_path #include
from django.contrib import admin
app_name = 'dac'
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('doctors/<slug:slug>', views.doctor, name='doctors'),
path('doctors/search/<slug:slug>/<slug:slug2>', views.doctor_search, name='doctors_search'),
re_path(r'^doctors_search/search/(?P<slug>.)/(?P<slug2>\d+)$', views.doctor_search, name='doctors_search'),
path('<slug:slug>', views.doctor_detail, name='doctor_detail'),
path('signup/', views.sign_up, name="sign_up"),
path('login/', views.log_in, name='log_in'),
path('logout/', views.log_out, name='log_out'),
path('reports/', views.reports, name='reports'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py:
def doctor(request, slug):
print("slug: ",slug)
if request.method == 'POST':
print("slug: ",slug)
risposta=request.POST.get("textAnswer")
risposta=risposta.upper()
risposta_list=risposta.rsplit()
print(risposta_list)
actual_url=request.build_absolute_uri()
url=re.sub("\d+$", "search/%s/1"%(risposta), actual_url)
return HttpResponseRedirect(url.encode('utf-8'))
slug=int(slug)
max_slug=int(round(doctors.objects.count()/28,0))
if slug==1:
prew_slug=slug
else:
prew_slug=slug-1
if slug==max_slug:
nxt_slug=max_slug
else:
nxt_slug=slug+1
doc_list=doctors.objects.all()[(slug-1)*28:slug*28]
{"doc_list":doc_list}
return render(request, 'dac/doctors.html', locals())
def doctor_search(request, slug, slug2):
slug2=int(slug2)
print("slug1: ",slug)
print("slug2: ",slug2)
if request.method=="POST":
risposta=request.POST.get("textAnswer")
risposta=risposta.upper()
actual_url=request.build_absolute_uri()
url=actual_url.replace(slug, risposta)
return HttpResponseRedirect(url.encode('utf-8'))
slug=urllib.parse.unquote(slug)
doc_list=doctors.objects.filter(frst_nm=slug) | doctors.objects.filter(lst_nm=slug) | doctors.objects.filter(pri_spec=slug)
if doc_list.count()==0:
messages.error(request, "no result")
max_slug=int(round(doc_list.count()/28,0))
if slug2==1:
prew_slug=slug2
else:
prew_slug=slug2-1
if slug2==max_slug:
nxt_slug=max_slug
else:
nxt_slug=slug2+1
doc_list=doc_list.all()[(slug2-1)*28:slug2*28]
{"doc_list":doc_list}
return render(request, 'dac/doctors_search.html', locals())
Let me explain better, when I visit the doctors page in which there is a search bar the doctor function is called, where if a word is entered and enter, the if condition occurs in the doctor function, which redirects to the url containing the word entered by the user, once redirected to the url: "search / 'answer' / 1 the doctor_search function is called in the view.py which takes the user's answer and the slug from the url, the problem arises when the user enters a word with space or special characters and django gives me 404 error

Use :
<str:var>
instead of :
<slug:var>
path('doctors/search/<str:slug>/<str:slug2>', views.doctor_search, name='doctors_search'),

Related

In my Django project I have two similar url

I have a question with my sites urls. When someone want to go mysite.com I redirect them to mysite.com/register.
url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'),
url(r'^register/',views.guaform2,name='custform2'),
Also I have another url that allows to write somethings after the part of register. For example when someone goes to this website mysite.com/register/kh-54-m2-fc it allows to go that:
url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'),
But when I use these urls together my guaform view doesn't work. And it goes to customer_form2.html. When someone goes this site: mysite.com/register/ anything I want them go to customer_form.html. How can I seperate these urls?
urls.py
from django.conf.urls import url
from django.contrib import admin
from olvapp import views
from django.views.generic import RedirectView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'),
url(r'^register/',views.guaform2,name='custform2'),
url(r'^register/(?P<pk>[-\w]+)',views.guaform,name='custform'),
]
views.py
from django.shortcuts import render,HttpResponse
from olvapp.models import Customer
from olvapp.forms import CustomerForm,CustomerForm2
from django.conf import settings
from django.http import HttpResponseRedirect
from django.urls import reverse
from olvapp import forms
def guaform(request,pk):
theurl = request.get_full_path()
orderid = theurl[10:]
form = CustomerForm(initial={'order_id':orderid})
if request.method == "POST":
form = CustomerForm(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect(reverse('thank'))
else:
HttpResponse("Error from invalid")
return render(request,'customer_form.html',{'form':form})
def guaform2(request):
form = CustomerForm2()
if request.method == "POST":
form = CustomerForm2(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect(reverse('thank'))
else:
HttpResponse("Error from invalid")
return render(request,'customer_form2.html',{'form':form})
It should be enough to lock down the regular expression so it doesn't match in both cases.
Tighten the custform2 regex by using an dollar sign on the end to mark the end of the input:
url(r'^register/$',views.guaform2,name='custform2'),
That should be enough to get things working

Issues with URLs in Django 3 when trying to view products detail page

New to Django and im trying to simply get to my products detail page using the following code in my URLs.py:
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from products import views
import carts
from carts.views import CartView
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('products/', views.all, name='products'),
path('s/', views.search, name='search'),
path('products/<slug:slug>', views.single, name='single_product'), <----This is the page I want to get to
path('cart/', carts.views.CartView, name='cart'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If its any help, this is the link I use in my template to get to the product display page View
And here is my view:
def single(request, slug):
try:
product = Product.objects.get(slug=slug)
images = ProductImage.objects.filter(product=product)
context = {'product': product, "images": images}
template = 'products/single.html'
return render(request, template, context)
except:
raise Http404
But when trying to access this page I get the following 404 Error:
Maybe a fresh pair of eyes can help me spot the mistake I'm making?
If any additional info is needed please let me know, I'll be happy to provide. Thanks a million in advance!
First try replacing:
path('products/<slug:slug>', views.single, name='single_product'),
with
path('products/<slug:slug>/', views.single, name='single_product'),
Django automatically appends a slash (/) to the end of urls by default and the image you showed us shows an url ending on a slash while your defined path does not contain one. I just tried to reproduce it, and this made it work.
And then if it still doesn't work, double check if you are using the correct slug to find your Product using the shell as you are raising a 404 whenever an exception occurs. You might even consider removing the try/except to check if it's actually raising a different exception.
Maybe the last slash ('/') is the problem, try the url without it:
http://127.0.0.1/products/product-one

404 error Django

I'm beginner in Django programing, and I want to show a view on my browser.
My code is:
polls/view.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def animal(request):
return HttpResponse("Hello cat")
polls/urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^animal$', views.animal, name='animal'),
)
When I show index view, everything in okay. But, when I show animal view, my browser not found the page, and I dont know why.
Thank you !
Your second URL pattern isn't terminated. It needs to be:
url(r'^animal/$', views.animal, name='animal')
also, you want to list your URLs from most specific to least specific. Also note that you can use the patterns prefix to keep your code a bit more DRY.
urlpatterns = patterns('views',
url(r'^animal/$', 'animal', name='animal'),
url(r'^$', 'index', name='index'),
)
as Django will try to match them top-down

django redirecting blank url to named url

I have my url:
url(r'^home/', HomeQuestionView, name='home_question') ,
When I enter localhost:8000/home I get my homepage but what I want is when I just enter I get my homepage.
I mean I want to redirect to the above homepage url when user enters only my site likewww.xyz.com not www.xyz.com/home
I dont want to configure in this way
url(r'^', HomeQuestionView, name='home_question') ,
Thanx in advance
Use generic RedirectView:
from django.views.generic.base import RedirectView
url(r'^$', RedirectView.as_view(url='/home/')),
I found this solution (long story short, you need to add views.py to your main project folder and make view which redirect your empty route to your url):
In your urls.py inside urlpatterns add this:
urlpatterns = [
...
path("", views.home, name="home"),
...
]
In main Django folder create views.py and import it in urls.py
example
In views.py add this code:
from django.shortcuts import render, redirect
def home(request):
return redirect("blog:index") # redirect to your page
Now every time your url will be empty like (localhost:8000) it will be redirected to (localhost:8000/your_adress). Also, you can use this not only with blank url, but anywhere you need this sort of redirection

Can't display new html page with href from homepage

The only examples I find. are related to issues with login page and iteration to other pages but not in the way I have the problem, so here is the issue I have to deal with -
I want to display a form for creating an account with multiple steps, using modals, when a user access the button "subscribe"
on my homepage.html I have this:
<a onClick="window.location.href='account'" target="_blank">
<input type="submit" value="account">
</a> `
...which is supposed to go to a new account.html page, in the same folder as my homepage.html
in my app's urls.py, where the apps' name is homepage I have:
from django.conf.urls import patterns, url
from homepage import views
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
url(r'^account$', views.account, name='account'),
)
and in my views I have:
from django.shortcuts import render
from homepage.models import Email
def tmp(request):
latest_email_list = Email.objects.order_by('-pub_date')[:0]
context = {'latest_email_list': latest_email_list}
return render(request, 'home_page/homepage.html', context)
def homepage(request):
return render(request, 'home_page/homepage.html')
def account(request):
return render(request, 'home_page/account.html')`
when I click on the button I get
Not Found
The requested URL /account was not found on this server.
I am a complete beginner in django and python so I really haven't yet wrapped my mind on how to work properly with the urls, views, and models together but I assume I have something wrongly defined in my views
would be grate if someone could help me setting this up,
Thanks
I only want to thank all those who took time to check my question and tried to give a solution.
I think it was my mistake that I did not post the code I have in my main urls.py file, so here it is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', include('home_page.urls', namespace="homepage")),
url(r'^admin/', include(admin.site.urls)),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Apparently, the problem was in that first prefix of the first url in the list:
I changed
url(r'^$'
for
url(r''
and now it calls whatever links I provide in my html pages.
Thanks all again

Categories