URl redirection issue in Django 2 - django

I'm new to Django and trying to build a web app with the following structure. I need your help to understand what Im doing wrong.
The flow of the application is shadesProductUploader.urls will forward '' to authSection for login and after a successful login user should be redirected to mainSection 'home/'.
Urls.py files are
shadesProductUploader.urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('authSection.urls')),
]
authSection.urls
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'authSection'
urlpatterns = [
path('', views.login_view, name='login'),
]
mainSection.urls
from django.contrib import admin
from django.urls import path,include
from . import views
app_name = 'mainSection'
urlpatterns = [
path('home/', views.home),
]
and the view.py in authSection
def login_view(request):
next = request.GET.get('next')
form = userLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
context={'user':user}
return redirect('home/')
return render(request, 'login.html', {'form': form})
after a successful login I get this error.
What Am I missing? Not sure why I see a Url of home/ home/

Update shadesProductUploader's main section url like this:
urlpatterns = [
path('',include('mainSection.urls')),
... # other urls
]
And change in mainSection urls like this:
urlpatterns = [
path('home/', views.home, name="home"), # <-- added name here
]
And in view, use it like this:
if next:
return redirect(next)
context={'user':user}
return redirect(reverse('home'))
Here, we have named our url as home. And we got the url using reverse.

Related

im getting error in django Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about/

code of project named carparts urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('parts.urls')),
]
code for my app named parts urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index,name='index'),
path('about', views.about,name='about'),
path('contact', views.contact,name='contact'),
]
code for views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
# return HttpResponse('this is home page')
def about(request):
return render(request, 'about.html')
def contact(request):
return render(request, 'contact.html')
index page code output is show in http://127.0.0.1:8000 but my about and contact page shows Page not found (404) . Can any one help me with this code.
Thank you
Joint '/' in your both urls.py like that:
urlpatterns = [
path('', views.index,name='index'),
path('about/', views.about,name='about'),
path('contact/', views.contact,name='contact'),
]
According Django Design philosophy on Definitive URLs:
Technically, foo.com/bar and foo.com/bar/ are two different URLs, and
search-engine robots (and some Web traffic-analyzing tools) would
treat them as separate pages. Django should make an effort to
“normalize” URLs so that search-engine robots don’t get confused.

Hello. I am having a problem to change the pages in my django project that it shows a page not found (404)

I've been building my first Django project, and I was doing the "login page", and it is working, but when then, I've made a condition that if the login is wrong, it comes back to the login page and shows an error message, and if it is right, it should go to a page where is written "logadissimo", but when I try this last one, I get the problem below:
Page not found (404) Request Method: GET Request
URL: http://localhost:8000/ Using the URLconf defined in sitetcc.urls,
Django tried these URL patterns, in this order:
admin/ login/ login/submit login/logado The empty path didn't match
any of these.
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
this is my url.py from the project:
"""
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.conf import include
from django.urls import path
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login_user),
path('login/submit', views.submit_login),
path('login/logado', views.logado)
]
the urls.py from the application:
from . import views
from django.urls import path
app_name = 'core'
urlpatterns = [
path('', views.login_user, name='login'),
path('', views.submit_login, name='submit'),
path('', views.logado, name='logado')
]
the views.py:
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import authenticate, login
from django.contrib import messages
# Create your views here.
def logado(request):
return render(request, 'logado.html')
def login_user(request):
return render(request,'login.html')
#csrf_protect
def submit_login(request):
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
print(password)
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('/logado/')
else:
messages.error(request,'Usuário e senha inválido. Favor tentar novamente:')
return redirect('/login/')
and a print screen with the folders' structure and the page "logado":
https://imgur.com/a/xAsBRHO
Thank you!
try return redirect('logado') and return redirect('login') syntax return redirect('your_view_name')
That's because you're passing a hardcoded URL (/logado/) to redirect that doesn't exists in your project's url.py, so Django can't match that route.
There are a couple of ways you can pass an argument to redirect, you can see some examples here. I strongly recommend you to use the name of your url's view, so in the future you can change the route of your path without any issues.
Also, you can declare your URLs like this, in that way you'll keep things clean and not bloat your project's urls.py.
Doing this you'll have your project's urls.py like this:
from django.contrib import admin
from django.urls.conf import include
from django.urls import path
from core import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', include('core.urls'),
]
And your application's urls.py like this:
from . import views
from django.urls import path
app_name = 'core'
urlpatterns = [
path('', views.login_user, name='login'),
path('login/submit/', views.submit_login, name='submit'),
path('login/logado/', views.logado, name='logado')
]
(Don't forget the trailing / at the end of each route)
Now you can call your view like this return redirect('core:logado')

Django is not showing the right path when clicking on a link

This is what it shows when you click on the link
Page not found (404)
Request Method: GET Request URL:
http://localhost:8000/jobapplication/new/1
Using the URLconf defined in careal.urls, Django tried these URL
patterns, in this order:
^$ [name='landing-index']
^admin/
^accounts/
^taskmanager/
^login/$ [name='login']
The problem is that I don't know why it is opening the link as http://localhost:8000/jobapplication/new/1, when it should be http://localhost:8000/taskmanager/jobapplication/new/1
This is what I have in the urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.auth import views as auth_views
from landingpage import views as landingpage_views
urlpatterns = [
url(r'^$', landingpage_views.index, name='landing-index'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^taskmanager/', include('taskmanager.urls')),
url(r'^login/$', auth_views.login, name='login'),
]
This is in urls.py in the app taskmanager
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'company/$', CompanyIndex.as_view(), name='company-index'),
url(r'company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]
And this is what I have in views.py in taskmanager, related to jobapplication
# Job Application views
class JobApplicationIndex(generic.ListView):
template_name = 'taskmanager/jobapplication_index.html'
def get_queryset(self):
if self.request.user.is_authenticated:
return JobApplication.objects.filter(user=self.request.user.id).order_by('-created_at')
class JobApplicationCreate(CreateView):
model = JobApplication
fields = ['jobpost', 'sent_date', 'deadline', 'success_rate']
def get_initial(self):
jobpost = get_object_or_404(JobPost, id=self.kwargs.get('jobpost_id'))
return {
'jobpost':jobpost,
}
def form_valid(self, form):
form.instance.user = self.request.user
return super(JobApplicationCreate, self).form_valid(form)
class JobApplicationDetails(generic.DetailView):
model = JobApplication
class JobApplicationEdit(UpdateView):
model = JobApplication
#fields = ['jobpostid', 'is_favorite']
#p = JobApplication.objects.get(id=jobpostid)
#p.is_favorite = is_favorite
#p.save()
class JobApplicationUpdate(UpdateView):
model = JobApplication
fields = ['sent_date', 'deadline', 'success_rate']
template_name_suffix = '_update_form'
def JobApplicationAdd(request, jobpost_id):
if request.method == 'GET' and request.user.is_authenticated:
# If job app for this id exists, redirect to that job app page with a message
if JobApplication.objects.filter(jobpost_id=int(jobpost_id)).exists():
existing = JobApplication.objects.get(jobpost_id=int(jobpost_id))
messages.add_message(request, messages.INFO, 'An application for this opening already exists.')
return HttpResponseRedirect(reverse('taskmanager:jobapplication-detail', args=[existing.id]))
jobapp = JobApplication(user=request.user, jobpost_id=int(jobpost_id), success_rate=50)
jobapp.save()
return HttpResponseRedirect(reverse('taskmanager:index'))
--- The thing is all the other links in taskmanager work and when you click on them, the right path is opened Eg: -
- http://localhost:8000/taskmanager/jobpost/
- http://localhost:8000/taskmanager/jobpost/2/
- http://localhost:8000/taskmanager/company/2/
- http://localhost:8000/taskmanager/kpi/
Try Adding an uptick in front of the regex patterns like you did for the ones that are working.
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'^jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'^jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'^jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'^jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'^company/$', CompanyIndex.as_view(), name='company-index'),
url(r'^company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'^jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]

Django redirect user to app based on permission and group

Say i have a django project which have 4 apps 1 app is for logging in
project urls:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^', include('Login.urls')),
url(r'^admin/', admin.site.urls),
]
settings:
LOGIN_REDIRECT_URL = '/'
login app urls:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
]
now say i have 3 apps based on user type i.e. Admin, Team Lead, Worker
so i want to redirect user based on their type of employment.
how can i achieve this ?
any help is appreciated
I guess that you will manually add/edit the user groups.
That can be done from django admin panel.
Here is the group/permission django docs: Permissions and Authorization
This is what I did:
I've created an index view in order to get the user group and redirect to the respective view that you want.
So, index view in views.py:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
group = request.user.groups.filter(user=request.user)[0]
if group.name=="employees":
return HttpResponseRedirect(reverse('worker'))
elif group.name=="teamLeader":
return HttpResponseRedirect(reverse('teamLeader'))
elif group.name=="admin":
return HttpResponseRedirect(reverse('adm'))
context = {}
template = "index.html"
return render(request, template, context)
And urls in urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from app import views as app_views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^$', app_views.index, name='index'),
url(r'^employees/$', app_views.employees, name='employees'),
url(r'^teamLeader/$', app_views.teamLeader, name='teamLeader'),
url(r'^adm/$', app_views.adm, name='adm'),
]
In settings.py
LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'
Is this what you want to do?

NoReverseMatch Django, get_success_url in CreateView

i create a create view in my blog app to create a post. in the
create view I used the function get_success_url. I want when i create
a post, that it will redirect to the blog_post_list. H
i get the error: NoReverseMatch
I guess it has to do sth with the urlpatterns.
main urls.py
from django.conf.urls import url, include
from django.contrib import admin
from blog.views import AboutPageView, ContactPageView
urlpatterns = [
url(r'', include('blog.urls', namespace='posts')),
url(r'^blog/', include('blog.urls', namespace='posts')),
url(r'^about/$', AboutPageView.as_view(), name='about'),
url(r'^contact/$', ContactPageView.as_view(), name='contact'),
#admin and login
url(r'^admin/', admin.site.urls),
]
urls in blog app
from django.conf.urls import url
from .views import blog_postListView, blog_postDetailView, blog_postCreateView
urlpatterns = [
url(r'^$', blog_postListView.as_view(), name='blog_post_list'),
url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'),
url(r'^(?P<slug>[-\w]+)$', blog_postDetailView.as_view(), name='detail'),
]
views in blogapp
class blog_postCreateView(CreateView):
#model = blog_post
form_class = blog_postForm
template_name = "form.html"
#fields = ["title", "content"]
def get_success_url(self):
return reverse("blog_post_list")
You haven't included the namespace so it isn't able to find the blog_post_list
So just add the namespace in the reverse call
reverse("posts:blog_post_list")
For more information on NoReverseMatch errors, see What is a NoReverseMatch error, and how do I fix it?