Django - creating a random page selector - python

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.

Related

Django 404 error even though I've created the path and view

I'm just beginning to learn Django.
I've created a simple web sub-app called 'flavo' inside of another one called 'djangoTest'
When I run http://127.0.0.1:8000/flavo
it correctly displays
Hello, World!
then when I run http://127.0.0.1:8000/flavo/a it should show
Hello, a!
But instead I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/flavo/a
Using the URLconf defined in testDjango.urls, Django tried these URL patterns, in this order:
admin/
flavo [name='index0']
flavo a [name='a']
The current path, flavo/a, didn’t match any of these.
in testDjango/hello/views.py I have
from django.http import HttpResponse
from django.shortcuts import render
def index0(request):
return HttpResponse("Hello, world!")
def a(request):
return HttpResponse("Hello, a!")
In testDjango/flavo/url/py I have
from django.urls import path
from . import views
urlpatterns = [
path("", views.index0, name="index0"),
path("a", views.a, name="a"),
]
The only other file I've changed is , testDjango/testDjango/urls.py"
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('flavo', include("flavo.urls")),
]
I'm confused why I can't access http://127.0.0.1:8000/flavo/a
Add '/'.
like this.
# testDjango/testDjango/urls.py
path('flavo/', include("flavo.urls"))

Page not found at /polls

I am a total beginner in "django" so I'm following some tutorials currently I' am watching https://youtu.be/JT80XhYJdBw Clever Programmer's tutorial which he follows django tutorial
Everything was cool until making a polls url
Code of views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
HttpResponse("Hello World.You're at the polls index")
Code of polls\urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Code of Mypr\urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/',admin.site.urls),
path('polls/',include('polls.urls')),
]
I don't get it I did the same thing but I'm getting error not only polls.In one turtorial he decided to make blog,and again the same error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in
this order:
admin/
The current path, polls/, didn't match any of these.
Please my seniors help me.
Note:I'm using the latest versions of django,windows and as editor I'm using Pycharm.
Already tried(and did not work):
from django.urls import path
from polls.views import index
urlpatterns = [
path('', index, name='index'),
]
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Using the URLconf defined in Mypr.urls, Django tried these URL patterns, in this order:
admin/
The current path, polls/, 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.
try to access polls/ URL in your browser then you will access the page
Because you have accessed the URL of your project, you have to go to this URL to access your app
try by changing your code like this
from django.urls import path
from polls.views import index
urlpatterns = [
path('', index, name='index'),
]
I was facing the same error. Feel kinda dumb after figuring out how to solve this.
Your urls.py content is all right
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
But it must be included in the mysite\mysite\urls.py and not in mysite\urls.py.
That means the inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it.

Trying to reach url with Path include() shows 404 in Django

first of I want to apologize if I use the wrong terms or words in my question. I'm completely new to Django and got only a few months of experience with python. I hope you can understand my question anyways. I also want to acknowledge the fact that I'm using some imports that are not needed here and might not be relevant to the latest version of Django, I'm starting to get lost in all the things I've tried from other threads to solve my problem.
I'm having some problems with showing a page from apps url.
I'm getting redirected to my homepage when trying to reach localhost:8000/articles (because /articles gives 404 error)
I'm not sure exactly what code I need to include here, so bear with me.
articles/urls.py and articles/views.py
from django.conf.urls import url
from django.urls import include, path
from django.conf.urls import include, url
from django.urls import path
from .import views
urlpatterns = [
path('^$', views.article_list),
]
from django.shortcuts import render
from django.http import HttpResponse
# views
def article_list(request):
return render(request, "articles/article_list.html")
The project's urls.py and project's views.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.urls import include, path
from django.conf.urls import include, url
from django.urls import path, re_path
from .import views
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
path('about/', views.about),
re_path('^.*$', views.homepage)
]
from django.http import HttpResponse
from django.shortcuts import render
#Views
def homepage(request):
# return HttpResponse('homepage')
return render(request, "homepage.html")
def about(request):
# return HttpResponse('about')
return render(request, "about.html")
Im getting no errors or such.
So, my question is - does anybody have a clue why /articles generate 404 error?
Thank you in advance.
Firstly, don't use ^$ with path(). You only use regular expressions with re_path.
path('', views.article_list),
Usually, /articles will be redirected to /articles/ with a trailing slash.
However, in your case, you have a catch-all pattern:
re_path('^.*$', views.homepage)
This matches /articles, so you see the home page. Note it's not redirected as you say in your answer, the browser bar will still show /articles.
Unless you have a really good reason to have the catch all, I suggest you remove it and change it to
re_path('^$', views.homepage),
or
path('', views.homepage),
That way, you'll see the homepage for localhost:8000, localhost:8000/articles will be redirected to localhost:8000/articles/, and you'll get a 404 for pages that don't exist, e.g. localhost:8000/art/
Just using a empty string '' instead of '^$:
urlpatterns = [
path('', views.article_list),
]
Take a look at the last example here: https://docs.djangoproject.com/en/3.1/topics/http/urls/#url-namespaces-and-included-urlconfs
*I don't know what django version are you using, but for regular expressions paths you should use re_path() https://docs.djangoproject.com/en/3.1/ref/urls/#django.urls.re_path

Not able to link a static web page using reverse_lazy

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;

Django: - NoReverseMatch error

I'm following the djangoforgirls.org tutorial on making my first django site. I'm trying the stage "extending your template" to make a link to an article within my website that uses the general template.
I keep get thrown the error: "NoReverseMatch at /, Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$']"
Some variable and file names may seem strange, the use of the website was music sampling but I used the tutorial's names for things in case that was what was wrong.
My urls.py for entire project:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('sample.urls')),
]
My urls.py for the specific app (sample):
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
My views.py for the app:
from django.utils import timezone
from .models import AudioSample
from django.shortcuts import render, get_object_or_404
def post_list(request):
samples = AudioSample.objects.order_by('length')
return render(request, 'blog/post_list.html', {'samples': samples})
def post_detail(request, pk):
post = get_object_or_404(AudioSample, pk=pk)
return render(request, 'blog/post.html', {'post': post})
And the line of code from the base template that's the link to another page in the website:
How to sample
I saw another person that asked this question with a similar project here and got it fixed but I dont understand the answer enough to make the change to mine (I dont understand what the namespace is).
If you have more than one urls.py, namespace can tell django how to handle the request. So in normally, namespace is the APP name.
In your project urls.py, try replacing r'' with r'^'. The former matches all urls, while the latter matches the start of the string.

Categories

Resources