I'm trying to develop a blog script with Django. But when I want to show post links, I get NoReverseMatch error.
My views.py
# -*- coding: utf-8 -*-
# Create your views here.
from .models import Yazi, Yorum, Kategori
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.contrib.sites.models import Site
def Home(request):
try:
posts = Yazi.objects.filter(yayinlanmis=True).order_by('-yayinlanma_tarihi')
except Yazi.DoesNotExist:
raise Http404
site = Site.objects.get_current()
c = RequestContext(request,{
'posts':posts,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_list.html', c)
def Detail(request, slug):
post = Yazi.objects.get(slug=slug)
site = Site.objects.get_current()
c= RequestContext(request,{
'posts':post,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_detail.html',c)
Urls.py in application folder.
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.Home,name='index'),
url(r'^/makale/(?P<slug>[0-9A-Za-z._%+-]+)$', views.Detail,name='detail'),
)
Urls.py in project folder
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('Penguencik_Yazilar.urls',namespace='blog')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And template code. What am I doing wrong?
{% load url from future %}
...
Read
Try to change this:
Read
to:
Read
Cause your view expect slug keyword here (?P<slug>[0-9A-Za-z._%+-]+).
Related
Below is my code. In my hello_world project there is two app pages. one is home page and another is profile page. home page is working fine, but profile page is showing error.
hello_world urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('home_page.urls',)),
path('profile_page',include('profile_page.urls',))
]
home page urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home page'),
]
home page views.py
from django.http import HttpResponse
def home(request):
return HttpResponse('home page')
profile page urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('profile_page',views.profile,name='profile page'),
]
profile page views.py
from django.http import HttpResponse
def profile(request):
return HttpResponse('profile page')
You need to use redirect method and include view name space as an argument..
Find the updated code:
from django.http import HttpResponse
def profile(request):
return redirect('profile page')
Don't forgot to import redirect...
The first argument of the path() function, i.e. the 'route' argument, must end with a forward slash.
path('profile_page/',include('profile_page.urls',))
Notice the forward slash at the end of the first argument, 'profile_page/'.
Your URLconf is not matching the expected pattern because of the missing slash.
How can I redirect the user to my custom 404.html page if he enters a wrong path ?
views.py:
from django.shortcuts import render, render_to_response, redirect
from django.template import RequestContext
import threading
def url_redirect(request):
return render_to_response('blog.html', RequestContext(request))
def post_redirect(request):
return render_to_response('post.html', RequestContext(request))
def privacy_redirect(request):
return render_to_response('privacy.html', RequestContext(request))
def terms_conditions_redirect(request):
return render_to_response('terms.html', RequestContext(request))
def page_404(request):
return render_to_response('404.html', RequestContext(request))
urls.py:
from __future__ import print_function
from cms.sitemaps import CMSSitemap
from django.conf.urls import *
from django.conf.urls.i18n import i18n_patterns
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns
admin.autodiscover()
urlpatterns = i18n_patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^select2/', include('django_select2.urls')),
url(r'^blog', "website.views.url_redirect", name="url-redirect"),
url(r'^post', "website.views.post_redirect", name="post-redirect"),
url(r'^privacy', "website.views.privacy_redirect", name="privacy-redirect"),
url(r'^terms', "website.views.terms_conditions_redirect", name="terms_conditions-redirect"),
url(r'^404', "website.views.page_404", name="page_404"),
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + staticfiles_urlpatterns() + urlpatterns
I also have TEMPLATE_DEBUG = True and DEBUG = False in my settings.py file. Any help, please ?
Also, can you guys tell me if those methods from views.py are ok or if they could be rewritten in a better way ?
Thanks
add 404.html near base.html (main folder templates)
and when there is an error 404 , Django itself take your 404 page
in settings.py
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['yourweb.com']
The code is
#urls.py
from django.conf.urls import patterns, url
from employees import views
from schdeules import views
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),
url(r'^accounts/$', 'django.views.generic.simple.redirect_to', {'url': '/'}),
url(r'^accounts/profile/$', 'django.views.generic.simple.redirect_to', {'url': '/'}),
)
#views.py
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
#login_required
def home(request):
welecome = 'hai welcome to opas'
context = {'temp_var': welecome}
return render(request, 'schdeules/home.html')
and iam getting an error
Exception Type: ViewDoesNotExist at /opas/
Exception Value: Could not import django.views.generic.simple.redirect_to. Parent module django.views.generic.simple does not exist.
i want to use django default login and logout modules.
if successfully logged in then i want to redirect to home page.
Thanks in advance.
The function-based generic view redirect_to was deprecated in Django 1.3, and removed in Django 1.5. Use the class-based generic view RedirectView instead.
from django.views.generic.base import RedirectView
urlpaterns = ('',
...
url(r'^accounts/$', RedirectView.as_view(url='/')),
url(r'^accounts/profile/$', RedirectView.as_view(url='/')),
)
Note that you don't have to include url patterns for /accounts/ and /accounts/profile/. You may be better to set LOGIN_REDIRECT_VIEW in your settings, so that users are redirected straight to the home page after logging in.
LOGIN_REDIRECT_VIEW = 'home' # using a named url pattern requires Django 1.5 or later
I've been working my way through the tutorials and thought that I'd understood the MVC framework. I have three models, two of which (Guests, Bookings) are populated. I can call data from Guests no problem. I tried to call data from Bookings and get ViewDoesNotExist at /bookings Tried booked_dates in module views. Error was: 'module' object has no attribute 'booked_dates'.
My urls are:
from django.conf.urls.defaults import *
#from views import current_datetime, people, detail, booked_dates
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('views',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^time/$','current_datetime'),
url(r'^mariners/$','people'),
url(r'^mariners/(?P<guest_id>\d+)/$','detail'),
url(r'^bookings/$','booked_dates'),
)
The views are:
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from guests.models import Guest, Booking, Price
import datetime
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return render_to_response('current_datetime.html', {'current_date': now})
def people(request):
guests_all = Guest.objects.all().order_by('last_name')
return render_to_response('guests_all.html', {'guests_all': guests_all})
def detail(request, guest_id):
g = get_object_or_404(Guest, pk=guest_id)
return render_to_response('guest_detail.html', {'detail' : g})
def booked_dates(request):
dates_all = Booking.objects.all().order_by('start_date')
return render_to_response('bookings.html', {'dates_all' : dates_all})
I haven't included the Models, but Booking is the correct class name, and start_date and end_date are correct.
I can't see an exact replica of this problem, and have tried numerous things to correct it, including a simple 'hello world' view, but I get the same error message.
I must be doing something wrong, but can't see what it might be. I've tried calling the views in a shell, which works.
Thanks for your help.
try including the app name with the view not just the view function
url(r'^bookings/$','guests.views.booked_dates'),
I'm trying to make a view redirect to another view so user's can't access it without a condition being met. In this case, a successful password change. I also want to achieve this using HttpResponseRedirect.
Now, I've never used reverse before, but I figured that this is the way to do that. Problem is that I can't get reverse to work. I get the following error:
ViewDoesNotExist at /account/password/
Could not import findadownload.main.views.foo. View does not exist in module findadownload.main.views.
# URLS
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
#SANDY
from findadownload.sandy.views import *
#TRIVIARIA
from findadownload.trivia.views import *
from findadownload.accounts.views import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'findadownload.main.views.presidium_home', name='presidium_home'),
(r'^web/$', 'findadownload.main.views.web'),
(r'^web/developers/$', sandy_developers),
#SANDY (for findadownload!)
(r'^get/sandy/$', get_sandy),
(r'^get/sandy/download/$', get_sandy_download),
(r'^sandy/register/$', sandy_registration),
(r'^sandy/complete/$', sandy_complete),
(r'^web/shared/$', sandy_shared_files),
(r'^web/remove/all/$', sandy_remove_all),
(r'^web/remove/(?P<file_id>\w+)/$', sandy_remove_file),
(r'^about/$', 'findadownload.main.views.about'),
(r'^pytech/$', 'findadownload.main.views.pytech'),
(r'^pytech/aboutus$', 'findadownload.main.views.pytech_about'),
(r'^pytech/services$', 'findadownload.main.views.pytech_services'),
(r'^pytech/support$', 'findadownload.main.views.pytech_support'),
(r'^pytech/contactus$', 'findadownload.main.views.pytech_contact'),
(r'^pytech/sitemap$', 'findadownload.main.views.pytech_sitemap'),
(r'^pytech/search/$', 'findadownload.main.views.pytech_search'),
(r'^presidium', 'findadownload.main.views.presidium_home'),
#TRIVIARIA
(r'^register/$', register),
(r'^login/$', login_view, {'template': 'trivia/registration/login.html'}),
(r'^logout/$', logout_view),
(r'^trivia/$', submit_question, {'template': 'trivia/trivia_questions.html'}),
(r'^challenges/$', submit_question, {'template': 'trivia/trivia_challenges.html'}),
(r'^question/thanks/$', question_thanks),
(r'^question/answer/$', submit_answer),
(r'^question/answer/result/(\d+)/(.*)/$', answer_result),
(r'^question/answer/challenge/$', challenge_answer),
(r'^account/$', upload_avatar),
(r'^account/password/$', password_change),
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success'),
(r'^(?P<username>\w+)/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/trivia/$', view_user_profile, {'template': 'trivia/trivia_view_user_questions.html'}),
(r'^(?P<username>\w+)/challenges/$', view_user_profile, {'template': 'trivia/trivia_view_user_challenges.html'}),
#FILE SHARING
(r'^web/share/(?P<file_id>\w+)/$', sandy_download),
(r'^web/report/(?P<file_id>\w+)/$', sandy_file_report),
(r'^web/like/(?P<file_id>\w+)/$', like_download),
#OTHER
(r'^web/profile/$', 'findadownload.main.views.web_profile'),
(r'^web/edit/$', 'findadownload.main.views.web_edit'),
(r'^trivia/$', 'findadownload.main.views.trivia_home', {'template': 'trivia/registration/index.html'}),
(r'^web/get/$', 'findadownload.main.views.web_get'),
(r'^web/progress/$', 'findadownload.main.views.web_progress'),
(r'^web/foo/$', 'findadownload.main.views.foo'),
(r'^web/search/$', 'findadownload.main.views.web_search'),
(r'^web/logout/$', 'findadownload.main.views.web_logout'),
(r'^web/resend/$', 'findadownload.main.views.web_resend'),
(r'^web/home/$', 'findadownload.main.views.web_home'),
(r'^web/history/$', 'findadownload.main.views.web_history'),
(r'^web/verify/(?P<link>\w+)/$', 'findadownload.main.views.web_activate'),
(r'^web/help/(?P<username>\w+)/$', 'findadownload.main.views.web_help'),
(r'^web/welcome/(?P<username>\w+)/$', 'findadownload.main.views.welcome'),
(r'^web/terms/$', 'findadownload.main.views.web_terms'),
(r'^web/privacy/$', 'findadownload.main.views.web_privacy'),
(r'^web/signup/$', 'findadownload.main.views.web_signup'),
(r'^web/login/$', 'findadownload.main.views.web_login'),
(r'^test$', 'findadownload.main.views.test'),
# url(r'^findadownload/', include('findadownload.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
if 1:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
'show_indexes': True,
}),
)
urlpatterns += staticfiles_urlpatterns()
# VIEWS
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from findadownload.accounts.forms import *
from django.contrib.auth.models import User
from django.contrib import auth
from findadownload.accounts.models import *
from django.core.urlresolvers import reverse
from findadownload.trivia.models import *
def password_success(request):
return render_to_response('trivia/trivia_password_success.html')
def password_change(request):
if request.user.is_authenticated():
# if for is submitted
if request.method == 'POST':
form = PasswordForm(user=request.user, data=request.POST)
# for the avatar part
if form.is_valid():
cd = form.cleaned_data
request.user.set_password(cd['confirm_password'])
request.user.save()`enter code here`
# redirect to profile page after POST
return HttpResponseRedirect(reverse('findadownload.accounts.views.password_success'))
else:
form = PasswordForm(user=request.user)
# render empty form
return render_to_response('trivia/trivia_password_change.html', {'form': form},
context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/login/?next=%s' % request.path)
You have to specify name kwargs in you url, in this case :
url(r'^account/password/success/$', 'findadownload.accounts.views.password_success', name = 'password_success')
Then use reverse like this :
return HttpResponseRedirect(reverse('password_success'))
What you pass in reverse is the name kwarg on urlpatterns.
EDIT:
Can i see the rest of your urls.py. I think the problem is not on reverse, because Django can't find view named foo.