Django reverse_lazy improperly configured - python

Under my once my user has signed up I would like to redirect them to the login page. However, reverse_lazy doesn't seem to be able to find my login path.
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUpView(CreateView):
form_class = forms.UserCreateForm
template_name = 'accounts/signup.html'
#Redirect login page once they have successfully signed up
succes_url = reverse_lazy('login')
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
path('signup/', views.SignUpView.as_view(template_name='accounts/signup.html'), name='signup'),
]

That is because you specified an app_name = …, in that case you prefix the name of the view with the namespace:
class SignUpView(CreateView):
# …
success_url = reverse_lazy('accounts:login')
You furthermore made a typo, it is success_url [Django-doc], not succes_url.

Related

Djnago : AttributeError: module 'django.views.generic' has no attribute 'Detail'

where can I import the detail attribute from?
views.py:
from django.shortcuts import render
from django.views import generic
from . import models
class Index(generic.TemplateView):
template_name='catalog/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['num_books'] = models.Book.objects.all().count()
context['num_instances'] = models.BookInstance.objects.all().count()
context['num_instances_available'] = models.BookInstance.objects.filter(status__exact='a').count()
context['num_authors'] = models.Author.objects.count()
return context
class BookListView(generic.ListView):
model = models.Book
template_name = 'catalog/book_list.html'
class BookDetialView(generic.Detail.View):
model= models.Book
template_name = 'catalog/book_detail.html'
urls.py
from django.urls import include, path, re_path
from . import views
from django.views.generic import TemplateView
app_name='catalog'
urlpatterns = [
path(r'', views.Index.as_view(), name='index'),
re_path(r'^$', views.Index.as_view(), name='index')
]
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'^books/$', views.BookListView.as_view(), name='books'),
path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
]
but the result:
class BookDetialView(generic.Detail.View):
AttributeError: module 'django.views.generic' has no attribute 'Detail'
Should be generic.DetailViewinstead of generic.Detail.View
In your BookDetailView you used generic.Detail.View instead of DetailView[Djano-doc].
Change your BookDetailView as
from django.views import generic
class BookDetialView(generic.DetailView): #<--- change here
model= models.Book
template_name = 'catalog/book_detail.html'
You have a couple of issues here.
(1) In your views you spell your view name as BookDetialView and in your url definition you spell it BookDetailView.
(2) I believe the correct inheritance is generic.DetailView instead of generic.Detail.View

Trying to trace a circular import error in Django Python

I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'

How to write primary key in django 2.0.2

the below code is working only for index page but it's not working for my DetailView. Please help me to fix (Using Django 2.0.2)
The below is my class for view:
from django.views import generic
from .models import Album
class IndexView(generic.ListView):
template_name = "newboston/index.html"
context_object_name = "all_album"
def get_queryset(self):
return Album.objects.all()
class DetailView(generic.DetailView):
model = Album
template_name = 'newboston/detail.html'
The below is my urls.py under my application.
from . import views
from django.urls import path
urlpatterns = [
path('', views.IndexView.as_view(), name='home'),
path('<slug:slug>/', views.DetailView.as_view(), name='detail'),
]
This is how you should refer to the primary key using pk in the urls.py file ...
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
Further details are in the documentation near the end of the page, or search for "polls/urls.py".

LoginView with Success

I am currently working with my Django authentification app. My goal is once the user logged in successful I want to redirect it to the index page where my code shows a customised message:
messages.success(request, 'Login Successful', extra_tags='alert alert-dark')
My problem is I didn't manage to 'access' LoginView in my views.py.
I read about SuccessMessageMixin, but this LoginView won't work (Template Not Found):
class LoginView(auth_views.LoginView):
template_name = "accounts/login.html"
Do you have any idea how to solve this?
Only as long I include template_name in my urls.py it works, but I can't add the success message mixin there.
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
]
You have a custom LoginView, but in the urls.py you call auth_views.LoginView.
To call your custom view you should do
from <module_name>.views import LoginView
urlpatterns = [
path('login/', LoginView.as_view(), name='login'),
]
It's a good idea to have a different name for your custom view, i.e.CustomLoginView.
You can add the followng snippet in the settings.py files:
LOGIN_REDIRECT_URL = '/'
You can add your own index page URL in 'LOGIN_REDIRECT_URL' variable

Django-reverse URL's

I'm experimenting with Django forms. I'm trying to create a form which will accept the name of a city as input and output coordinates as output. My apps name is rango. I'm having a lot of trouble in URL reverse after accepting the input of the form..
My project/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import os
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/',include('rango.urls', namespace="rango")),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
My rango/urls.py (rango is the name of the app):
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^welcome/$', views.index, name='index'),
url(r'^about/$', views.about, name='about_page'),
url(r'^categories/(?P<name_dir>\w+)/$',views.cats,name='cats'),
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
url(r'^disp_page/$', views.disp_page, name='disp_page')
My forms.py:
from django import forms
from rango.models import Page, Category
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the name of the city.")
#url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
#views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
exclude = ('category','url','views')
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category,Page
from pygeocoder import Geocoder
from rango.forms import PageForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import operator
# Create your views here.
def geo(request,city):
context = RequestContext(request)
citydata=Geocoder.geocode(city)
codtuple=citydata[0].coordinates
codtuple=list(codtuple)
context_dict = {'cood':codtuple}
return render_to_response('coods.html',context_dict,context)
def disp_page(request):
# A HTTP POST?
if request.method == 'POST':
form = PageForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
#form.save(commit=True)
city = form.cleaned_data['title']
# context = RequestContext(request)
#citydata=Geocoder.geocode(cityname)
#codtuple=citydata[0].coordinates
#codtuple=list(codtuple)
#context_dict = {'cood':codtuple}
return HttpResponseRedirect(reverse('rango:geo', args=(request,city)))
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = PageForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'disp_page.html', {'form': form})
Basically the disp_page displays the form. I type the name of a city in the form(EX:NEWYORK) and then it has to redirect to the "geo" function in my views.py which would output the coordinates in a different view. This redirection doesn't seem to be happening. Any help is appreciated!!
change this line
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
in rango/urls.py to :
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='geo'),
and use :
return HttpResponseRedirect(reverse('rango:geo', args=(city,)))

Categories