Not able to link a static web page using reverse_lazy - python

I have written some code to develop a social media site. In that, I wanted to redirect to homepage look-a-like which i have created. I tried to create a url for this page, but there is no use. I am getting the error like:
NoReverseMatch at /accounts/signup/
Reverse for 'start' not found. 'start' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 1.11.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'start' not found. 'start' is not a valid view function or pattern name.
In this project, there are three apps. Among them, "accounts" is one app. In accounts, I have created the templates folder with three files.("login.html,signup.html and start.html"). The views.py file for this :
from django.contrib.auth import login, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import CreateView
from . import forms
from django.views.generic import TemplateView
class MyView(TemplateView):
template_name = 'accounts/start.html'
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("start")
template_name = "accounts/signup.html"
And the urls.py file is:
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"),
url(r"start/$", views.MyView.as_view(), name="start")
]
How to redirect to "start.html" page from the signup page. I have created start view but still, it is showing error as above. Please help me with this.

url(r'^start/$', views.MyView.as_view(), name="start")
reverse_lazy("accounts:start")
^ for pattern start,$ for pattern end;You use namespaced url,see Reversing namespaced URLs;

Related

Why do errors differ when I interchange the order of the members of url patterns

Note: I'm not requesting for a help to fix the errors, but to ask the reason why they differ by interchanging the order of url patterns.
The following is how my urls.py of my django application (basic_app) looks like:
from django.urls import path, re_path
from basic_app import views
app_name = 'basic_app'
urlpatterns = [
path('', views.SchoolListView.as_view(), name='list'),
re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'),
path('create/', views.SchoolCreateView.as_view(), name='create'),
]
when I run the server and type in the url http://127.0.0.1:8000/basic_app/create/, it throws the following error:
ValueError at /basic_app/create/
Field 'id' expected a number but got 'create'.
Request Method: GET
Request URL: http://127.0.0.1:8000/basic_app/create/
Django Version: 3.2.4
Exception Type: ValueError
Exception Value:
Field 'id' expected a number but got 'create'.
Interestingly when I interchanged the order of the 2nd and 3rd url patterns as follows:
from django.urls import path, re_path
from basic_app import views
app_name = 'basic_app'
urlpatterns = [
path('', views.SchoolListView.as_view(), name='list'),
path('create/', views.SchoolCreateView.as_view(), name='create'),
re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'),
]
I got a different error:
ImproperlyConfigured at /basic_app/create/
Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited.
Request Method: GET
Request URL: http://127.0.0.1:8000/basic_app/create/
Django Version: 3.2.4
Exception Type: ImproperlyConfigured
Exception Value:
Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited.
I am new to django and curious about this event. Why doen't python let create/ go to the next pattern to check since it did not fit the first pattern?
My views.py file looks like this:
from django.shortcuts import render
from django.views.generic import (
View,
TemplateView,
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
from . import models
# Create your views here.
class IndexView(TemplateView):
template_name = 'index.html'
class SchoolListView(ListView):
context_object_name = 'schools'
model = models.School
class SchoolDetailView(DetailView):
context_object_name = 'school_detail'
model = models.School
template_name = 'basic_app/school_detail.html'
class SchoolCreateView(CreateView):
model = models.School
Django aims to match url's top to bottom. If you thus visit /basic_app/create/, and the rule with the SchoolDetailView is first, it will fire that view, since create/ matches with the regex (?P<pk>[-\w+])/$. Since the primary key of your object is likely an AutoField, it makes no sense to match a create/ with pk, since we expect this to be an integer.
Another problem is that your SchoolCreateView is not configured correctly, you need to specify what fields will be used in the CreateView, so we can implement this with:
class SchoolCreateView(CreateView):
model = models.School
fields = '__all__'
We can refine the re_path of the detail view to only be triggered with an int, not with an arbitrary slug:
re_path(r'^(?P<pk>\d+)/$', views.SchoolDetailView.as_view(), name='detail'),
or wiht a path converter:
path(r'<int:pk>/', views.SchoolDetailView.as_view(), name='detail'),

why am I getting a 404 when looking for the id of an object django

I cannot get the liftview to work, the test page is working fine. Am I missing an import into the views? I have data in the database with an id of 1 (picture included to show).
#polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('test', views.test, name='test'),
path('<int:lift_id>/', views.liftview, name='liftview'),
]
#views.py
from django.http import HttpResponse
def liftview(request, lift_id):
return HttpResponse("lift id")
def test(request):
return HttpResponse("test")
#models.py
import datetime
from django.db import models
from django.utils import timezone
class Lift(models.Model):
lift_name = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.lift_name
Traceback:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/liftview
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
polls/ [name='index']
polls/ test [name='test']
polls/ <int:lift_id>/ [name='liftview']
The current path, polls/1/liftview, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
there is data w/an id of 1..
In your polls/urls.py you have defined your path as
path('<int:lift_id>/', views.liftview, name='liftview'),
Therefore, you can access this path by going to http://127.0.0.1:8000/polls/1/ and not http://127.0.0.1:8000/polls/1/liftview
If you want to access this path on http://127.0.0.1:8000/polls/1/liftview then in your polls/urls.py change the path to
path('<int:lift_id>/liftview', views.liftview, name='liftview'),

Django - creating a random page selector

I'm hoping to create a link on a homepage that, when clicked, will randomly redirect the user to 1 out of 5 entry pages (CSS, Django, Git, HTML, Python) on the site.
I saw someone else asking essentially the same question (select an random page with django) and I tried to follow the 2 answers but now when I click on my Random Page link I have an error:
NoReverseMatch at /wiki/random/
Reverse for 'index' with arguments '('Git',)' not found. 2 pattern(s) tried: ['wiki/random/$', 'wiki/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/wiki/random/
Exception Type: NoReverseMatch
views.py
from django.urls import reverse
from django.http import HttpResponseRedirect
from . import util
import random
def random_page (request):
entries = util.list_entries()
selected_page = random.choice(entries)
return HttpResponseRedirect (reverse('index', args=[selected_page]))
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("css/", views.css, name="CSS"),
path("django/", views.django, name="Django"),
path("git/", views.git, name="Git"),
path("html/", views.html, name="HTML"),
path("python/", views.python, name="Python"),
path("createnew/", views.createnew, name="New_Entry"),
path("random/", views.random_page, name="index")
]
layout.html
<div>
Random Page
</div>
I was a little worried about making the homepage and random_page have the same name "index" but even when I changed the name in views.py to "random" and then changed it in layouts.html it still didn't work.

Linking outer html page to the reverse_lazy() of signup page

I have written code to develop a social media clone site using django. In that, after signup, i have to move to homepage instead of login page. The homepage html code is present in another folder outside of this current folder. I am unable to access the url of the html page from this. The code is:
from django.contrib.auth import login, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import CreateView
from . import forms
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("login")
template_name = "accounts/signup.html"
Instead of "login", the url should be "base". The path of "login.html" is: "project/accounts/templates/accounts/login.html". And the path of "base.html" is: "project/templates/project/base.html". Please suggest me a method to modify this.
You need to create the according URL and view, so you can redirect to that view:
# views.py
from django.views.generic import TemplateView
class MyView(TemplateView):
template_name = 'project/base.html'
# urls.py
from django.conf.urls import url
from .views import MyView
urlpatterns += url(r'^my_url/', MyView.as_view(), name='my_view')
# signup view
from django.contrib.auth import login, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import CreateView
from . import forms
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy("my_view")
template_name = "accounts/signup.html"
You may need to adapt a couple things, but the key is, that you need a URL and a View so you can redirect them there, once they signed up.
You should use it with your application name.
url:
path('email-listesi/kayit-silindi/', UnsubscriptionSuccessful.as_view(), name='unsubscription-successful'),
views:
success_url = reverse_lazy('yourapplicationname:unsubscription-successful')

What more do I need to do to have Django's #login_required decorator work?

I am trying to use Django's account system, including the #login_required decorator. My settings.py file includes django.contrib.auth and I have done a syncdb.
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/accounts/login/?next=/
Using the URLconf defined in dashboard.urls, Django tried these URL patterns, in this order:
^$ [name='home']
The current URL, accounts/login/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I see the above after trying to #login_required-decorate my home view.
It seems to be choking because it is redirected to accounts/login/, which I have not prepared for in my urls.py.
What can I add to urls.py or elsewhere so that the login_required decorator will do its usual behaviour?
Thanks,
Set the LOGIN_URL in your settings. The default value is '/accounts/login/'
The decorator also takes an optional login_url argument:
#login_required(login_url='/accounts/login/')
And, from the docs:
Note that if you don’t specify the login_url parameter, you’ll need to
ensure that the settings.LOGIN_URL and your login view are properly
associated. For example, using the defaults, add the following line to
your URLconf:
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
path('accounts/login/', admin.site.urls),
Add this line in your urls.py project folder. Then it will work fine.
from django.contrib.auth.decorators import login_required
#login_required(login_url='/accounts/login/')
Add above two lines in your views.py file.
What worked for me in Django 2.2.1 - include re_path('^accounts/', admin.site.urls), in my project urls.py:
urls.py
from django.conf import settings
from django.conf.urls import include
from django.conf.urls import re_path
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
re_path('^accounts/', admin.site.urls),
]
And in my views.py:
views.py
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
#method_decorator(login_required, name='dispatch')
class HomePageView(TemplateView):
"""
Home Page View
"""
template_name = 'amp/home.html'
Hope that helps.
UPDATE: To avoid warnings from django in regards to admin urls being loaded twice, I used a redirect instead in urls.py:
urls.py
urlpatterns = [
re_path('^accounts/', admin.site.urls),
re_path(r'^admin/', RedirectView.as_view(url='/accounts/', permanent=True))
]
More on redirect view here.

Categories

Resources