How to place links in django templates - python

VERY new to Django and I am a little confused. I have placed a link in my html template file; however, clicking the link reports a 404 error.
App views.py file:
from django.shortcuts import render
def index(request):
return render(request, "login/index.html", None)
def terms(request):
return render(request, "login/terms.html", None)
App urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
path('', views.terms, name="terms")
]
Offending code in index.html:
By signing in, you agree to our Terms Of Use Policy
Clicking on the link pops a 404 error. Any help would be appreciated as I learn a new framework.

The first problem is that both the path to the views.index and views.terms share the same path. As a result, you have made views.terms inaccessible.
You thus should change one of the paths, for example:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('terms/', views.terms, name='terms')
]
You better use the {% url ... %} template tag [Django-doc] to resolve the URLs, since if you later decide to change the path of a certain view, you can still calculate the path.
In your template, you thus write:
By signing in, you agree to our Terms Of Use Policy

urlpatterns = [
path('', views.index, name="index"),
path('terms/', views.terms, name="terms")
]
By signing in, you agree to our Terms Of Use Policy
or

Related

django urls without a trailing slash show Page not found

in django urls without a trailing slash in the end i get this result "Page not found 404"
the same project and the same code in one pc i get different result.
this code is when i get the page without slash:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
]
and this the same code but i should to add slash
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]
what i am waiting in the frontend its my views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def about(request):
return HttpResponse('about page')
i am waiting for your help guys
This behaviour is controlled by the APPEND_SLASH setting. In the default setting APPEND_SLASH is set to True which means if the requested URL does not match any paths set in urls.py an HTTP redirect will issue to the same URL with a trailing slash.
Eg:
Assume a request to /foo.com/bar will redirect to /foo.com/bar/ in case the provided URL /foo.com/bar is an invalid URL pattern.
Documentation states that
Note that the redirect may cause any data submitted in a POST request to be lost.
The APPEND_SLASH setting is only used if CommonMiddleware is installed (see Middleware). See also PREPEND_WWW.
please read the documentation for further clarification.

Every url in a django app only renders home.html

So, I am not really lucky with latest django version tutorials, so I've had some problems with things that changed between some versions. One of this things is: althought I do exactly as I read/watch in the tutorials I always get the same result - all urls redirect to the same HTML page.
Here is my root urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('theblog.urls')),
]
Here is my app urls:
from django.conf.urls import url, include
from .views import HomeView, ArticleDetailView
urlpatterns = [
url('', HomeView.as_view(), name='home'),
url('^article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'),
]
For example, when I go to localhost:8000/articles/1 (or any other pk), it renders home.html (HomeView class) as if it was localhost:8000/.
Hope you can help me. Thanks!
There are two things wrong with your code.
url('^article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'),
This will not work. If you want to use url. you can't use <int:pk>, you need to use a RegEx:
url("article/([0-9]+)/", ArticleDetailView.as_view(), name="article-detail")
Note that this will be deprecated in the future and if you are using django >=2.0 you should use path:
path("article/<int:article>/", ArticleDetailView.as_view(), name="article-detail")
However this will still direct you to the wrong view. django stops after the first URL pattern match.
Switch them around to fix that:
urlpatterns = [
url("article/([0-9]+)/", ArticleDetailView.as_view(), name="article-detail"),
# path("article/<int:article>/", ArticleDetailView.as_view(), name="article-detail"), # alternative with path instead of url
url('', HomeView.as_view(), name='home')
]
It may be due to this line
url('', HomeView.as_view(), name='home'),
Because url wraps re_path there may be some logic which will treat the blank regex string as a wildcard. Try changing it to '/'
url('/', HomeView.as_view(), name='home'),

When I try to write something in Django urls.py file, it doesn't show this in the browser

#code in urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name= 'index'),
path('about/', views.about, name ='about'),
]
#code in views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
def about(request):
return HttpResponse("about harry")
Body
I am doing this while watching a tutorial, and the same thing is working for him. Moreover, if mistakenly I write the wrong code and run, cmd shows the errors and on reloading the browser the server doesn't work more. Then I need to restart CMD and again run manage.py. Please tell me the reason and also the solution, Thanks.
What errors do you get?
Besides there're 2 urls' files: url routes for pages are inside urls.py in the same folder where views.py are. In another urls.py (the one which is in the same folder with manage.py) you may need to write following, assuming that 'polls' is the name of you application:
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
]
According to Django docs: include() function allows referencing other URLconfs. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
If you still get the error: check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/

Why am I getting a 404 error when trying to access my website's domain name, yet if I domain name/home it works?

Okay... let's try to explain things clearly. I've used Python Django to create a dynamic webpage/web-app. After completing the website I have published it using DigitalOcean and have successfully attached my purchased domain name to the name server of DigitalOcean. When I access my website, ordinanceservices.com, i get an error 404; however, if I type ordinanceservices.com/home it works as it should and displays the home page. How, by editing the python files, can I have it to where ordinanceservices.com will display the home page as opposed to error 404? I feel like there's something that I am doing that is fundamentally wrong regarding my .urls structure and thus a rewrite/redirect in the nginx config should not be necessary.
Here is the specific error:
Page not found (404)
Request Method: GET
Request URL: http://ordinanceservices.com/
Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order:
^admin/
^ ^home/ [name='home']
^ ^contact/ [name='contact']
^ ^services/ [name='services']
The current URL, , didn't match any of these.
I somewhat understand what is happening here though I do not know how to fix this. Next I will provide my .urls files for each folder that contains such:
/django_project urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('company.urls')),
)
/company urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^home/', views.home, name='home'),
url(r'^contact/', views.contact, name='contact'),
url(r'^services/', views.services, name='services'),
]
/company views.py
from django.shortcuts import render
def home(request):
return render(request, 'company/home.html')
def contact(request):
return render(request, 'company/contact.html')
def services(request):
return render(request, 'company/services.html')
What I am aiming to do, without needing to redirect the main URL using the nginx config files to do so, is to edit my urls and views structure of my Python files to ensure that the normal URL, ordinanceservices.com, will actually display a page; preferably the home page of my webpage.
I have a hunch that it has to do with the fact that I do not have a views.index for the r'^admin/' to reach to. I am not certain but I have been trying to figure this out for hours. Does anyone have a clue what I can do to fix this?
You haven't defined anything at the root url. Add one more line to your company urls.py so it becomes
//company urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^home/', views.home, name='home'),
url(r'^contact/', views.contact, name='contact'),
url(r'^services/', views.services, name='services'),
]
First of all, check if you have added www.yourdomain.com or yourdomain.com to ALLOWED_HOST = ['www.yourdomain.com','yourdomain.com'] in your settings.py
and then in your company/urls.py do this
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^services/$', views.services, name='services'),
]
and in your main urls.py add this code
from django.conf.urls import url,include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('company.urls')),
]

Django redirecting everything to homepage

I'm stuck with a Django project, I tried to add another app called login to make a login page but for some reason the page just redirects to the homepage except for the admin page
For example: 127.0.0.1:8000 will go to the homepage but 127.0.0.1:8000/login will also display the homepage even though I linked another template to it.
Here is my code:
main urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('portal.urls')),
url(r'^login/', include('login.urls')),
]
login urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/', views.index, name="login"),
]
login views.py
from django.shortcuts import render
def index(request):
return render(request, 'login/login.html')
portal urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^', views.index, name="portal"),
]
I see 2 problems here:
As #DanielRoseman mentioned above, the regular expression ^ matches anything, so you should change it to ^$.
When you use an include, the rest of the path after what the include matched is passed to the included pattern. You’ll want to use ^$ in your login urls.py too.
You don't terminate the portal index URL, so it matches everything. It should be:
url(r'^$', views.index, name="portal"),
In addition, if the regex is login/$ but you enter http ://server/login, then it won't match wheras http://server/login/ will.
You could try changing the regex to login/*$, which will match any number (even zero) / on the end of the url.
So http: //server/login, http: //server/login/, http: //server/login//// would all match.
Or if you want to be specific, login/{0,1}$ might work (though that regex syntax is from memory!)

Categories