The problem with my code is that I keep getting a "page not found (404) error, the path 'post/...' does not match" when I try to click on a hyperlink on my posts page. I made 3 posts. Could it be the regex? Because I'm currently not good at regex.
How can I match the views.py to the correct path in urlpatterns?
My urls.py is:
from django.contrib import admin
from django.urls import path, re_path
from blog import views as blog_views
urlpatterns = [
path('post/', blog_views.post),
re_path(r'^post(.*)/$', blog_views.post),
path('about/'. blog_views.about),
path('', blog_views.index),
path('admin/', admin.site.urls)
]
My views.py is:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Post
def index(request):
posts = Post.objects.all()
return render(request,'index.html', {'posts': posts})
def post(request, slug):
print(slug)
return render ('post.html',{'post': get_object_or_404(Post, slug=slug)})
def about(request):
return render(request, 'about.html', {})
You could use something like:
re_path(r'post/(?P<slug>[\w-]+)/$', blog_views.posts),
Do you really need to use re_path here? It would be simpler to use path:
path('post/<slug:slug>/', blog_views.post),
Related
Here are the two views :
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
class sectionOfficer_home(View):
def get(self, request, *args, **kwargs):
return render(request, 'sectionofficer/UI/index.html', {})
class sectionOfficer_main(View):
def get(self, request, *args, **kwargs):
return render(request, 'sectionofficer/UI/404.html', {})
Here is my urls.py of the app sectionOfficer:
from django.urls import path
from .views import (sectionOfficer_home, sectionOfficer_main)
app_name= 'sectionofficer'
urlpatterns = [
path('', sectionOfficer_home.as_view(), name = "sectionofc"),
path('secmain', sectionOfficer_main.as_view(), name = "secmain")
]
And here is the global urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('sectionoffc', include('sectionofficer.urls')),
path('secmain', include('sectionofficer.urls')),
]
But it showing always the first view template for any different url. What is wrong here ? Help please.
I think i tired everything in trying to solve this problem.
I'm getting a NoReverseMatch i understand its from my "urls" but that's basically it, I was using url() instead of path().at the end of it all i just made a mess of my code.
view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Topic as TopicModel
from .forms import TopicForms
# Create your views here.
def index(request):
""""the home page for learning app"""
return render(request,'learning_logs/index.html')
def topics(request):
topics = TopicModel.objects.order_by('date_added')
context = {'topics' : topics}
return render(request, 'learning_logs/topics.html',context)
def topic(request, topic_id):
"""show a single topic ans all its entries"""
topic = TopicModel.objects.get(id=topic_id)
entries = topic.entry_set.order_by('date_added')
context = {'topic':topic, 'entries': entries}
return render(request,'learning_logs/topic.html',context)
def new_topic(request):
"""add a new topic"""
if request.method != 'POST':
#no data submitted ; create a black form
form = TopicForms
else:
#POST data submited ; process data
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_log:topics'))
context = {'form': form }
return render(request,'learning_log/new_topic.html', context)
urls.py
#defins URL patterns for learning log
from django.conf.urls import url
from . import views
from django.urls import path
app_name = 'learning_log'
urlpatterns = [
#home page
path('', views.index, name ='index'),
#url(r'^$', views.index, name='index.html'),
#show topics
path('topics/',views.topics, name ='topics'),
# url(r'^topics/$',views.topics, name='topics.html'),
path('topics/<topic_id>',views.topic, name = 'topic'),
#url(r'^topics/(?P<topic_id>\d+)\$',views.topic,name='topic.html'),
path('topics/',views.new_topic, name = 'new_topic'),
#url(r'^topics/$',views.new_topic, name='new_topic.html'),
]
main urls.py
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
path('', include('learning_logs.urls')),
path('admin/',admin.site.urls),
]
please anything I'm doing wrong plus any books or tutorials i can read because i think the book im using is outdated
Your app_name inside the urls file is "learning_log" but it seems your html folders are in learning_logs. Maybe something to do with that? Also can you make sure the app_name exists in your INSTALLED_APPS?
I've done a Udemy course for Django which was good for me but they are not free if you want to learn more.
just add the include param called namespace in your main urls.py for the app.
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
path('', include('learning_logs.urls', namespace="learning_log")),
path('admin/',admin.site.urls),
]
here you have the documentation of URLs namespaces: https://docs.djangoproject.com/en/3.2/topics/http/urls/#url-namespaces
If you don't want to set the namespace you must call the url like this: reverse('topics')
Hi there I created a decorator to protect a certain view from unauthorized persons though I am using django allauth to handle my authentications so I've used its login url. On testing whether the authorization works instead of redirecting me to the login page Localhost gets stuck in a redirect loop
here is a look at my code
decorators.py
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
def seller_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='account_login'):
'''
Decorator for views that checks that the logged in user is a seller,
redirects to the log-in page if necessary.
'''
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_seller,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
views.py
from django.views.generic import CreateView,DetailView, ListView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .decorators import seller_required
#method_decorator( seller_required , name='dispatch')
class SellerDashBoardView(ListView):
model = Seller
template_name = 'seller_dashboard.html'
App level urls
from django.urls import path
from .views import SellerSignUpView, SellerDashBoardView
urlpatterns = [
path('seller_reg/', SellerSignUpView.as_view(), name='seller_reg'),
path('seller/', SellerDashBoardView.as_view(), name='seller_dash')
]
project level urls
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('user.urls')),
#path('users/', include('django.contrib.auth.urls')),
path('accounts/', include('allauth.urls')),
path('', include('pages.urls')),
path('store/', include('store.urls')),
#path("djangorave/", include("djangorave.urls", namespace="djangorave")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When starting the server, an error crashes, which file and piece of code should I pay attention to? Other answers given on this site did not help.
Terminal:
File "/home/lab/ProjectsDjango/env_bookmarks/dj-bookmarks/bookmarks/account/urls.py", line 7, in <module>
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
File "/home/lab/ProjectsDjango/env_bookmarks/bookmarks/lib/python3.8/site-packages/django/conf/urls/__init__.py", line 22, in url
return re_path(regex, view, kwargs, name)
File "/home/lab/ProjectsDjango/env_bookmarks/bookmarks/lib/python3.8/site-packages/django/urls/conf.py", line 73, in _path
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().
Next is my application code.
Main urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^account/', include('account.urls')),
]
App views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'], password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
App urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#url(r'^login/$', views.user_login, name='login'),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
url(r'^$', views.dashboard, name='dashboard'),
]
Maybe I'm looking in the wrong place and trying to find a bug where it isn't?
I am assuming you are using django>1.9: You cannot use strings as views. So you need to do something like this with all views:
from django.contrib.auth import login, logout
urlpatterns = [
url(r'^login/$', login, name='login'),
url(r'^logout/$', logout, name='logout'),
......
]
I have a problem where my url is seen as an invalid url. None of my URLS are working for my Django Application. I have made the mistake of using the same secret key that I used for another application. Here is a picture of my error message, url page, and my views.
Error Message
urls.py
views.py
from django.shortcuts import render
from home.models import Products
#This is the store view
def home(request):
return render(request,'home.html')
#This is the About Us page view
def AboutUs(request):
return render(request,'AboutUs.html')
#This is the Long Arm Services View
def LongArmServices(request):
return render(request,'LongArmServices.html')
#This is the product View
def product(request):
return render(request,'product.html')
urls.py:
from django.urls import path
from . import views
from django.http import HttpResponse
app_name='home'
urlpatterns = [
path('',views.home,name='home'),
path('about_us/',views.AboutUs,name='AboutUs'), path('long_arm_services/',views.LongArmServices,name='LongArmServices'),
path('product/',views.product,name='product'),
]
Your urls.py specify an app_name = 'home', so that means you need to prefix the name of the view with the app_name and a colon (:). So you should rewrite the marked part in the template to:
href="{% url 'home:home' %}"