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
Related
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'),
What is the best practice for migration from request to django.views.generic?
How implement django.views.generic for logoutPage/loginPage if earlier used request?
#This my model.py
from django.db import models
from django.contrib.auth.models import User
#This my view.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import *
from django.contrib.auth import login,logout,authenticate
from .forms import *
from django.views.generic import ListView
def logoutPage(request):
logout(request)
return redirect('/')
def loginPage(request):
if request.user.is_authenticated:
return redirect('home')
else:
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(request,username=username,password=password)
if user is not None:
print("working")
login(request,user)
return redirect('/')
context={}
return render(request,'book/templates/login.html',context)
You can try the simplest way or a slightly more complicated but giving more possibilities in the future.
If you don't need any modifications (and usually one doesn't at early stage), you can do it directly in your main urls.py file:
from django.contrib.auth import views as auth_views
urlpatterns = [
...
path('login/', auth_views.LoginView.as_view(template_name='book/templates/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
Alternatively you can create your own classes, that inherit from that views. Obviously, you can set proper path() for each in urls.py.
from django.contrib.auth import views as auth_views
class LoginPage(auth_views.LoginView):
template_name='book/templates/login.html'
...
class LoginPage(auth_views.LogoutView):
...
For both you can set redirect page with variables set in settings.py with wanted path name (it means the name="welcome" part):
LOGIN_REDIRECT_URL = "user_profile"
LOGOUT_REDIRECT_URL = "come_back_please"
After filling the page should appear 'done', but i have an error message:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/candidate/done.html
The current path, candidate/done.html, didn't match any of these.
Can't configure redirect to 'done' page.
Here views.py:
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import AnketaForm
from .models import Anketa
def anketa_create_view(request):
if request.method == 'POST':
form = AnketaForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('candidate/done.html')
else:
form = AnketaForm()
return render(request, 'candidate/anketa_create.html', {'form': form})
urls.py (apps/candidate)
from django.urls import path
from . import views
urlpatterns = [
path('', views.anketa_create_view, name = 'anketa_create_view'),
]
urls.py
from django.contrib import admin
from django.urls import path, include
from candidate.views import anketa_create_view
urlpatterns = [
path('done/', anketa_create_view),
path('', anketa_create_view),
path('grappelli/', include('grappelli.urls')),
path('admin/', admin.site.urls),
]
you need to give a name to the done url
path('done/', anketa_create_view, name='done'),
and can do with reverse
return HttpResponseRedirect(reverse('done'))
or you can do redirect shortcut
return redirect('done')
Remove in urls.py
path('done/', anketa_create_view)
and replace in views.py
return HttpResponseRedirect('candidate/done.html')
to
return render(request, 'candidate/done.html', {})
I'm working on a site that would display some data on my database and a form where people can contact me.
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
from django.utils import timezone
from .models import Logo, SkillLanguages, SkillAPI, SkillFrameworks,
WorkPortfolio, PersonalPortfolio
def index(request):
logo=Logo.objects.all()
skill_languages=SkillLanguages.objects.all()
skill_api=SkillAPI.objects.all()
skill_frameworks=SkillFrameworks.objects.all()
work_portfolio=WorkPortfolio.objects.all()
personal_portfolio=PersonalPortfolio.objects.all()
return render(request, 'johann/index.html', {'logo': logo, 'skill_languages': skill_languages, 'skill_api': skill_api, 'skill_frameworks': skill_frameworks, 'work_portfolio': work_portfolio, 'personal_portfolio': personal_portfolio})
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(name, message, from_email, ['myemail#notsuspiciousmailserver.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "johann/index.html", {'form': form})
def success(request):
return HttpResponse('<script>alert("Success! Thank you for your message."); window.location = "https://pqdrl7qd.apps.lair.io/#contact";</script>')
urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.email, name='email'),
url(r'^success/$', views.success, name='success'),
]
I found out that my problem lies in what I did to the first two URLs, if I switched the email URL and the index URL's places my template would then display my form instead of the data stored in my models and vice versa. What can I do about this?
You have two url patterns that are identical
url(r'^$', views.index, name='index'),
url(r'^$', views.email, name='email'),
They will be evaluated in order and the index view will always match first. Once a match is found, the rest of the url patterns are ignored.
You need to come up with a different route for your email view. Might I suggest
url(r'^email/$', views.email, name='email'),
You can use:
url(r'^$', views.index, name='index'),
url(r'^email/$', views.email, name='email'),
I'm experimenting with Django forms. I'm trying to create a form which will accept the name of a city as input and output coordinates as output. My apps name is rango. I'm having a lot of trouble in URL reverse after accepting the input of the form..
My project/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import os
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/',include('rango.urls', namespace="rango")),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
My rango/urls.py (rango is the name of the app):
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^welcome/$', views.index, name='index'),
url(r'^about/$', views.about, name='about_page'),
url(r'^categories/(?P<name_dir>\w+)/$',views.cats,name='cats'),
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
url(r'^disp_page/$', views.disp_page, name='disp_page')
My forms.py:
from django import forms
from rango.models import Page, Category
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the name of the city.")
#url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
#views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
exclude = ('category','url','views')
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category,Page
from pygeocoder import Geocoder
from rango.forms import PageForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import operator
# Create your views here.
def geo(request,city):
context = RequestContext(request)
citydata=Geocoder.geocode(city)
codtuple=citydata[0].coordinates
codtuple=list(codtuple)
context_dict = {'cood':codtuple}
return render_to_response('coods.html',context_dict,context)
def disp_page(request):
# A HTTP POST?
if request.method == 'POST':
form = PageForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
#form.save(commit=True)
city = form.cleaned_data['title']
# context = RequestContext(request)
#citydata=Geocoder.geocode(cityname)
#codtuple=citydata[0].coordinates
#codtuple=list(codtuple)
#context_dict = {'cood':codtuple}
return HttpResponseRedirect(reverse('rango:geo', args=(request,city)))
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = PageForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'disp_page.html', {'form': form})
Basically the disp_page displays the form. I type the name of a city in the form(EX:NEWYORK) and then it has to redirect to the "geo" function in my views.py which would output the coordinates in a different view. This redirection doesn't seem to be happening. Any help is appreciated!!
change this line
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
in rango/urls.py to :
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='geo'),
and use :
return HttpResponseRedirect(reverse('rango:geo', args=(city,)))