Django-reverse URL's - python

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,)))

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

HttpResponseRedirect в Django. Can't do redirect on 'done' page

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', {})

404 Page Not Found "GET /accounts/login/?next=/profile/ HTTP/1.1" 404

I am getting some issues with my urls. I don't have any 'account/' route but i when I want to visit 'login/' and after logging in it should redirect me to my profile... but it is taking me to this route: "http://127.0.0.1:8000/accounts/login/?next=/profile/"
I am sorry if I've posted any unnecessary kinds of stuff:
mainapp.urls
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from forms.views import RegisterView,LoginView
from django.conf import settings
from django.conf.urls.static import static
from user_profile import views as profile_views
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',RegisterView.as_view(), name='register'),
path('login/', LoginView.as_view(), name = 'login'),
path('profile/',profile_views.profile,name='profile'),
path('updateprofile/',profile_views.updateprofile,name='update_profile'),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
forms.views(Login/Logout)View
from django.shortcuts import render, redirect,reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, get_user_model, logout
from django.utils.http import is_safe_url
from django.contrib.auth.decorators import login_required
from django.views.generic import CreateView, FormView
from .models import User
from .forms import RegisterForm,LoginForm
class LoginView(FormView):
form_class = LoginForm #instance
template_name = 'forms/login.html'
success_url = '/profile/'
def User_logout(request):
if request.method == "POST":
logout(request)
return redirect(reverse('login'))
LoginForm:
class LoginForm(forms.Form):
email = forms.EmailField(label='email')
password = forms.CharField(widget=forms.PasswordInput)
def form_valid(self,form):
request=self.request
next_=request.GET.get('next')
next_post=request.POST.get('next')
redirect_path=next_ or next_post or None
email=form.cleaned_data.get('email')
password=form.cleaned_data.get('password')
user=authenticate(username=email, password=password)
if user is not None:
login(request, user)
try:
del request.session['UserProfile.html']
except:
pass
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("login")
return super(LoginView, self).form_invalid(form)
set a variable in your urls.py of you mainapp as following
appname='mainapp'
now in your login view add following
def get_success_url(self):
return reverse('mainapp:profile')
Currently, in Django 3.2, the reverse method is written this way:
def get_success_url(self):
return reverse('profile')
No need to add appname var in your urls.py

Email form wont display on template

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'),

Invalid syntax error in Django form class

SyntaxError at /
invalid syntax (forms.py, line 5)
Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 1.6.1
Exception Type: SyntaxError
Exception Value:
invalid syntax (forms.py, line 5)
ExceptionLocation: C:\Users\chiragbagla\Desktop\skillshare\src\signups\views.py in <module>, line 5
Python Executable: C:\Users\chiragbagla\Desktop\skillshare\Scripts\python2.exe
Python Version: 2.7.9
A part of my view.py code is as follows
from django.shortcuts import render, render_to_response, RequestContext
# Create your views here.
from .forms import SignUpForm
def home(request):
form = SignUpForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return render_to_response("signup.html", locals(), context_instance=RequestContext(request))
A part of my forms.py code is as follows
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class meta:
model=SignUp
A part of my url.py code is as follows
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'signups.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I want to display sign up form on webpage which I have created using signup.html but the form is not displaying on the webpage of my browser.
So, please tell me where the mistake I am making???
Like the error points out:
class meta:
Should be...
class Meta:

Categories