Page is not found - django

I have the following urls:
urlspatterns=[ path('<str:urlsername>/', views.profile, name='profile'),
path('login/', auth_views.LoginView.as_view(),name ='login'),
path('logout/', auth_views.LogoutView.as_view()),
path('password_change/', auth_views.PasswordChangeView.as_view(),name='password_change'),]
In views for the first url I have this:
def profile(request, username):
user = get_object_or_404(User, username = username)
posts = Post.objects.filter(author = user).order_by('-pub_date')
return render(request,'profile.html', {'posts':posts,'user':user})
So when I go to the page login, logout or password_change I get the error "Page is not found"
Request Method: GET
Request URL: http://127.0.0.1:8000/password_change/
Raised by: posts.views.profile
But if I comment the profile view and its url everything works just fine. Why does the url 'logout' etc goes to profile view?

I think password_change will match <str:urlsername> first.
So the solution is change your urlspatterns to the code bellow.
urlspatterns=[
path('login/', auth_views.LoginView.as_view(),name ='login'),
path('logout/', auth_views.LogoutView.as_view()),
path('password_change/', auth_views.PasswordChangeView.as_view(),name='password_change'),
path('<str:urlsername>/', views.profile, name='profile')
]

Related

Function in Django Views causing others to throw 404 errors

I have a weird bug where one view:
def view_dashboard (request, username):
# If no such user exists raise 404
try:
user = User.objects.get(username=username)
print(user)
except:
raise Http404
template = 'testingland/dashboard.html'
return render (request, template)
Is causing others to throw 404 errors when I visit their urls. Note: I get a 404 when I visit the above view's connected url but also when I visit another view's url. For instance, visiting the url associated with this view also throws a 404:
def write_description(request):
return render(request, 'testingland/write_description.html')
Here are my url.py:
urlpatterns = [
path('index', views.cafes_home, name='cafes_home'),
path('', views.index_2, name='cafes_home'),
path('venue/<int:venue_id>/', views.venue_page, name='venue_page'),
url('electra/cafe_list/', views.cafe_list.as_view(), name='cafe_list'),
url('electra/marker_info/', views.marker_info, name='marker_info'),
url('electra/info_box/', views.info_box, name='info_box'),
url('electra/new_marker/', views.new_marker, name='new_marker'),
url('electra/broadsheet_scraper/', views.broadsheet_scraper, name='broadsheet_scraper'),
url('electra/get_cafe/', views.get_cafe, name='get_cafe'),
url('add_cafe', views.add_cafe, name='add_cafe'),
url('add_description', views.add_description, name='add_description'),
url('add_image', views.add_image, name='add_image'),
url('add_broadsheet', views.add_broadsheet, name='add_broadsheet'),
url('add_broadsheet', views.add_broadsheet, name='add_broadsheet'),
path('profile', views.profile, name='profile'),
path('users', views.users, name='users'),
path('<username>', views.view_dashboard, name='view_dashboard'),
url('electra/get_users/', views.get_users, name='get_users'),
path('electra/getUserMarkers/', views.getUserMarkers, name='getUserMarkers'),
#auth
path('signup', views.SignUp.as_view(), name='signup'),
path('login', auth.views.LoginView.as_view(), name='login'),
path('logout', auth.views.LogoutView.as_view(), name='logout'),
#placelist
path('write_description', views.write_description, name='write_description'),
# path('write_image', views.write_image, name='write_image'),
path('broadsheet', views.broadsheet, name='broadsheet'),
path('<int:pk>', views.DetailList.as_view(), name='detail_list'),
path('<int:pk>/update', views.UpdateList.as_view(), name='update_list'),
path('<int:pk>/delete', views.DeleteList.as_view(), name='delete_list'),
]
Here is the error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/dashboard
Raised by: testingland.views.view_dashboard

how to specifiy this url in django 127.0.0.1:8000/?uid=Mjg&token=5dj-ddf5e0d6cf0d6f03dfc1

Some URLs configured in my django project are like so:
path('<str:uid>/<str:token>/', views.activate,name="activate")
path('login/', LoginView.as_view(template_name='blog/login.html'), name='login'),
path('logout/', LogoutView.as_view(template_name='blog/logout.html'), name='logout'),
path('signup/', views.signup,name="blog-home"),
path('<str:uid>/<str:token>/', views.activate,name="activate")
Attempting to load 127.0.0.1:8000/?uid=Mjg&token=5dj-ddf5e0d6cf0d6f03dfc1 shows the debug page. How to write url config for this?
Because those are query string parameters. You can access them with request.GET.get('uid') and request.GET.get('token') in your views.
I would put the URL like
path('', views.activate, name='activate')
and the view:
def activate(request):
uid = request.GET.get('uid', None)
token = request.GET.get('token', None)
# All the other logic
And then handle in the view what to do if I have those parameters, etc.
With your current URL (path('<str:uid>/<str:token>/', views.activate,name="activate")) what you are expecting is something like: 127.0.0.1/Mjg/5dj-ddf5e0d6

How to extend django.contrib.auth views?

How I've Arranged Templates : I have placed my login.html in /templates/registration folder of Django. So, the Django takes necessary care of accounts/login ,accounts/logout url requests and renders as per request. And I haven't to code for the individual login and logout functions.
What I am trying to Achieve : I want to authenticate users at login request, when they requests the login page:
If user is anonymous user, I want to render the normal login page.
However, If the user is authenticated thats already logged in. I want to display an error and not the logged page.
I want to achieve this in the views.py and urls.py and not in the templates by:
{% if user.is_authenticated %}
{% if user.is_anonymous %}
Urls.py
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
urlpatterns=[
url(r'^register/$', views.register, name='register'),
url(r'^logout/$', auth_views.logout, {'next_page' : 'Homepage'}, name='logout'),
]
You can wrap the view with your own, which either redirects or calls the original.
def wrapped_login(request):
if request.user.is_authenticated:
return redirect('whatever')
else:
return auth_views.login(request)
Provide LOGIN_REDIRECT_URL = '/' in settings.py. Then use the following url for login page:
urlpatterns = [
url(r'^login/',
auth_views.LoginView.as_view(redirect_authenticated_user=True),
name='login'),
]
This will redirect your user to the URL provided in settings file if they try to login even after being authenticated.

Django LOGIN_REDIRECT_URL failing when redirecting to the users profile

I'm using django-registration-redux and have most of it working. I'm trying to redirect to the user profile after login. Currently the URL for user profile is:
url(r'^user/(\w+)/$', views.profile, name='profile'),
...and the view for the profile is:
def profile(request, username):
user = get_object_or_404(User, username=username)
products = Product.objects.filter(user=user)
if not request.user == user:
return render(request, 'no.html')
else:
return render(request, 'profile.html', {'user':user,'products': products})
I've added LOGIN_REDIRECT_URL = 'profile' to settings.py but am getting the error:
Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['user/(\\w+)/$']
I've gone around this so many times I'm totally confused. I could simply set LOGIN_REDIRECT_URL = 'home' and be done with it, but then I wouldn't have gotten past this error. Do I need to create a different view for this?
EDIT:
If I set LOGIN_REDIRECT_URL to 'home' or 'products' or any other URL it works - just not for 'profile'. Here's my urls.py:
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^designers/', views.DesignersView.as_view(), name='designers'),
url(r'^subscribe/$', views.subscribe, name='subscribe'),
url(r'^products/$', views.products, name = 'products'),
url(r'^product/$', ProductListView.as_view(), name='product_list'),
url(r'^user/(\w+)/$', views.profile, name='profile'),
url(r'post_url/', views.post_product, name='post_product'),
url(r'^([0-9]+)/$', views.detail, name = 'detail'),
url(r'^like_product/$', views.like_product, name='like_product' ),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='product-edit'),
url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='product-delete'),
]
I'm still searching - just not finding a solution, yet.
Finally found a way to do this. I created a login view in my views.py:
from django.contrib.auth.views import LoginView
class LoginView(LoginView):
def get_success_url(self):
return reverse('profile', args=[self.request.user.username])
Also added this to my urls.py to reflect the new view:
url(r'^accounts/login/$', LoginView.as_view(), name='login'),
Removed LOGIN_REDIRECT_URL from settings.py and it worked.
Your regex url isn't correct. Change:
url(r'^user/(\w+)/$', views.profile, name='profile'),
To
url(r'^user/(?P<username>[\w\-]+)/$', views.profile, name='profile'),

Django can't find redirect url when authenticating user

I am trying to login protect some of my pages, including my dashboard. Here is the view for my dashboard at the root of my site: sitename.com/
#login_required
def index(request):
print(request.session['user_email'])
context_dict = {}
return render(request, 'dashboard/index.html', context_dict)
My project url file:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^job/', include('job.urls')),
url(r'^welcome/', include('welcome.urls')), //the app for logging in
url(r'^$', include('dashboard.urls')), //main dashboard app
# s
]
My dashboard app url file:
urlpatterns = [
url(r'$', views.index, name='index'),
url(r'^signup/$', views.signup, name='signup'),
url(r'^login/$', views.auth_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
]
When I try and logout and then go to / I get a message saying that http://127.0.0.1:8000/welcome?next=/ doesn't match any urls in my project urls file. So the login check is working, it just can't figure out the url when the GET variable next is set.
As you are using django's default login from contrib.auth, try passing next as an extra_context dict.
url(r'^login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html', 'extra_context': {'next':'/'}})
Another solution is to specify login url in login_required decorator itself
#login_required(login_url='/login/')
def index(request):
print(request.session['user_email'])
context_dict = {}
return render(request, 'dashboard/index.html', context_dict)
Let know if this solve your issue. HTH :)
I finally got it to work. This is my routes:
Welcome app routes (app for logging in/out)
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup/$', views.signup, name='signup'),
url(r'^/login/$', views.auth_login, name='login'),
url(r'^/logout', views.user_logout, name='logout'),
]
Main routes for the entire project:
urlpatterns = [
url(r'^welcome', include('welcome.urls')),
url(r'^', include('dashboard.urls')),
]
Now I don't get any errors with the next variable in the url:
http://127.0.0.1:8000/welcome?next=/
I have a javascript file grabbing the value of next and redirecting to it if the user logs in successfully. *I use ajax to authenticate the user.