Django - Why doesn't reverse work? - django

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.

Related

Redirect to custom 404 html page in DjangoCMS

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

Django NoReverseMatch Error

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._%+-]+).

How to redirect users to a specific url after registration in django registration?

So I am using django-registration app to implement a user registration page for my site. I used Django's backends.simple views which allows the users to immediately login after registration. My question is how do I redirect them to my other app's page located in the same directory as the project.
Here is what my main urls.py looks like:
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'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# 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)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
fileupload is the name of the other app I have in the project directory mysite.
This is what the backends.simple.urls looks like:
"""
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.
If you'd like to customize registration behavior, feel free to set up
your own URL patterns for these views instead.
"""
from django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import TemplateView
from registration.backends.simple.views import RegistrationView
urlpatterns = patterns('',
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'),
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
)
And here is the backends.simple.views:
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User
from registration import signals
from registration.views import RegistrationView as BaseRegistrationView
class RegistrationView(BaseRegistrationView):
"""
A registration backend which implements the simplest possible
workflow: a user supplies a username, email address and password
(the bare minimum for a useful account), and is immediately signed
up and logged in).
"""
def register(self, request, **cleaned_data):
username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
User.objects.create_user(username, email, password)
new_user = authenticate(username=username, password=password)
login(request, new_user)
signals.user_registered.send(sender=self.__class__,
user=new_user,
request=request)
return new_user
def registration_allowed(self, request):
"""
Indicate whether account registration is currently permitted,
based on the value of the setting ``REGISTRATION_OPEN``. This
is determined as follows:
* If ``REGISTRATION_OPEN`` is not specified in settings, or is
set to ``True``, registration is permitted.
* If ``REGISTRATION_OPEN`` is both specified and set to
``False``, registration is not permitted.
"""
return getattr(settings, 'REGISTRATION_OPEN', True)
def get_success_url(self, request, user):
return (user.get_absolute_url(), (), {})
I tried the changing the get_success_url function to just return the url I want which is /upload/new but it still redirected me to users/insert username page and gave an error. How do I redirect the user to the upload/new page where the other app resides after registration?
Don't change the code in the registration module. Instead, subclass the RegistrationView, and override the get_success_url method to return the url you want.
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
return "/upload/new"
Then include your custom registration view in your main urls.py, instead of including the simple backend urls.
urlpatterns = [
# your custom registration view
url(r'^register/$', MyRegistrationView.as_view(), name='registration_register'),
# the rest of the views from the simple backend
url(r'^register/closed/$', TemplateView.as_view(template_name='registration/registration_closed.html'),
name='registration_disallowed'),
url(r'', include('registration.auth_urls')),
]
I am using django_registration 3.1 package. I have posted all 3 files (views.py urls.py forms.py) that are needed to use this package.
To redirect user to a custom url on successfull registration, create a view that subclasses RegistrationView. Pass in a success_url of your choice.
Views.py:
from django_registration.backends.one_step.views import RegistrationView
from django.urls import reverse_lazy
class MyRegistrationView(RegistrationView):
success_url = reverse_lazy('homepage:homepage') # using reverse() will give error
urls.py:
from django.urls import path, include
from django_registration.backends.one_step.views import RegistrationView
from core.forms import CustomUserForm
from .views import MyRegistrationView
app_name = 'core'
urlpatterns = [
# login using rest api
path('api/', include('core.api.urls')),
# register for our custom class
path('auth/register/', MyRegistrationView.as_view(
form_class=CustomUserForm
), name='django_registration_register'),
path('auth/', include('django_registration.backends.one_step.urls')),
path('auth/', include('django.contrib.auth.urls'))
]
forms.py:
from django_registration.forms import RegistrationForm
from core.models import CustomUser
class CustomUserForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
model = CustomUser
You can set SIMPLE_BACKEND_REDIRECT_URL in settings.py.
settings.py
SIMPLE_BACKEND_REDIRECT_URL = '/upload/new'
If you wish, you can modify the following file /usr/local/lib/python2.7/dist-packages/registration/backends/simple/urls.py, changing the path, for example:
Before modifying:
success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/'),
After modifying:
success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/upload/new'),
Regards.
Diego

Adding simple views in django

I am getting started on django and this is how my view is looking like
from django.template import Context, loader
from datetime import datetime
from django.http import HttpResponse
def hello_view(request):
""" Simple Hello World View """
t = loader.get_template('helloworld.html')
c = Context({
'current_time': datetime.now(),
})
return HttpResponse(t.render(c))
def detail_view(request):
return HttpResponse("You're looking at detail view")
My urls.py file looks like this
from django.conf.urls import patterns, include, url
from posted.views import hello_view
#from posted.views import detail_view
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', view=hello_view, name='hello_page'),
#url(r'^$', view=detail_view, name='detail_page'),
# url(r'^posts/', include('posts.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)),
)
When i run the server and visit http://example.com:8000/ ,the hello_view gets displayed.I want my urls to be of the form http://example.com:8000/hello or http://example.com:8000/detail. Do i need .htaccess to achieve that?.
I have fixed the issue somewhat with this while i study what Daniel suggested i look at.
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
(r'^detail/', TemplateView.as_view(template_name="detail.html")),
# url(r'^posts/', include('posts.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)),
)

__init__() takes exactly 1 argument (3 given)

Error
response = callback(request,*callback_args,**callback_kwargs)
Exception Type: TypeError at /accounts/profile/
Exception Value: __init__() takes exactly 1 argument (3 given)
Here is my code
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset, password_reset_done, password_change, password_change_done
from django.views.generic import TemplateView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('registration.urls')),
(r'^accounts/profile/$', TemplateView, {'template': 'registration/profile.html'}),
(r'^accounts/password_reset/$', password_reset, {'template_name': 'registration/password_reset.html'}),
(r'^accounts/password_reset_done/$', password_reset_done, {'template_name': 'registration/password_reset_done.html'}),
(r'^accounts/password_change/$', password_change, {'template_name': 'registration/password_change.html'}),
(r'^accounts/password_change_done/$', password_change_done, {'template_name': 'registration/password_change_done.html'}),
)
views.py
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from models import RegistrationProfile
from forms import RegistrationForm
from django.core.context_processors import csrf
def activate(request, activation_key):
activation_key = activation_key.lower() # Normalize before trying anything with it.
account = RegistrationProfile.objects.activate_user(activation_key)
return render_to_response('registration/activate.html',{
'account': account,
'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS
}, context_instance=RequestContext(request))
c = {} c.update(csrf(request))
def register(request, success_url='/accounts/register/complete/'):
form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
new_user=RegistrationProfile.objects.create_inactive_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect(success_url)
return render_to_response('registration/registration_form.html', {
'form': form
}, context_instance=RequestContext(request))
Your current error is caused by passing TemplateView into your url conf. It should be TemplateView.as_view().
urlpatterns = patterns('',
#...
(r'^accounts/profile/$', TemplateView.as_view(template= 'registration/profile.html')),
#...
)