Function in Django Views causing others to throw 404 errors - django

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

Related

Cannot understand error when url is changed in django. It throws '404'

When I first created the urls with 'pk' they worked fine.
But when I use 'slug' for lookup, when I change the url it throws 404.
from django.urls import path
from .views import (ProductListView, ProductDetailView,
ProductFeaturedListView, ProductFeaturedDetailView)
app_name = 'products'
urlpatterns = [
path('', ProductListView.as_view(),
name='list'),
path('detail/<str:slug>/', ProductDetailView.as_view(),
name='detail'),
path('featured/', ProductFeaturedListView.as_view(),
name='featured-list'),
path('featured/<str:slug>/', ProductFeaturedDetailView.as_view(),
name='featured-detail')
]
Now when I change the 'product-detail' url, the feature url throws error which is irrelevant. And it says that this particular view is causing it. But the view has no relation with 'featured-product-list' url.
from .views import (ProductListView, ProductDetailView,
ProductFeaturedListView, ProductFeaturedDetailView)
app_name = 'products'
urlpatterns = [
path('', ProductListView.as_view(),
name='list'),
path('<str:slug>/', ProductDetailView.as_view(),
name='detail'),
path('featured/', ProductFeaturedListView.as_view(),
name='featured-list'),
path('featured/<str:slug>/', ProductFeaturedDetailView.as_view(),
name='featured-detail')
]
error
On diagnosing it I find that it is trying to pass 'featured' as a slug, which is out of my logic.
Please help me to find what is causing this issue.
here is the detailed error
class ProductDetailView(DetailView):
template_name = 'products/product_detail.html'
def get_object(self):
slug = self.kwargs.get('slug')
try:
instance = Product.objects.all().get(slug=slug)
except Product.DoesNotExist:
raise Http404('Not Found...')
except Exception:
raise Http404('huh?')
return instance

Page is not found

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

Reverse for 'detail' with arguments '('accounts/<int:pk>/',)' not found. 1 pattern(s) tried: ['accounts/(?P<pk>[0-9]+)/$']

In my blog, i want when someone clicks on read more, it should direct the person to the log in page, which is working fine, then after inputting the log in credentials, it should take the person to the detail page and this where I'm getting the error above.
this is the code
urls.py
from . import views
from django.urls import path
from.views import Home, Detail, CreatePost
urlpatterns = [
path('', Home.as_view(), name='home'),
path('register/', views.register, name='register'),
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout'),
path('post/', CreatePost.as_view(success_url='/'), name='post'),
path('accounts/<int:pk>/', Detail.as_view(), name='detail'),
]
The line below is from the entry_list.html
Read More →
Then below is my login logic
```
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('detail', 'accounts/<int:pk>/')
else:
return redirect('login')
else:
return render(request, 'login.html')
```
path('accounts/<int:pk>/', Detail.as_view(), name='detail')
In that url definition, <int:pk> is a placeholder for the user id; it is not literally part of the url.
To redirect to the url, you must supply the user id:
return redirect('detail', pk=user.id)

How do I redirect errors like 404 or 500 or 403 to a custom error page in apache httpd?

I have created a Django project but I am using Apache as the webserver. Can anyone tell me how can I redirect an error code like 404 or 500 or 400 to a custom error html page instead of getting a standard error message on page in case an error was to occur ? I've tried the solutions available on the web but none seems to work
I have a blog supported by django,in project's urls.py:
from django.conf.urls import handler400, handler403, handler404, handler500
urlpatterns = [
url(r'^$', IndexView.as_view(), name='index'),
url(r'^admin/', admin.site.urls),
....
url(r'^rss/$', BlogFeed(), name='rss'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='sitemap')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if not settings.DEBUG:
handler400 = 'common.views.bad_request'
handler403 = 'common.views.permission_denied'
handler404 = 'common.views.page_not_found'
handler500 = 'common.views.server_error'
common/views.py:
def bad_request(request):
context = {}
return render(request, '400.html', context, status=400)
def permission_denied(request):
context = {}
return render(request, '403.html', context, status=403)
def page_not_found(request):
context = {}
return render(request, '404.html', context, status=404)
def server_error(request):
context = {}
return render(request, '500.html', context, status=500)
from django.conf.urls import (handler403, handler404, handler500)
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'
You can handle the requests like this.
The exception missing in a view is a solution for this problem.
Change:
def bad_request(request):
for:
def bad_request(request, exception):

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