how to design Django url pattern to avoid 301 - django

I have a project called blog, the url pattern shows below. I want to make the app "posts" to route all the traffic.
Url patterns of them shows below:
#blog/urls.py
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('posts.url', namespace='posts')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#posts/url.py
from django.conf.urls import url
from django.contrib import admin
from .views import (
home,
down,
get_data_by_post,
)
urlpatterns = [
url(r'^$', home, name='down'),
url(r'^api/$', ins_down, name='api'),
url(r'^p/(?P<slug>[-\w]+)/$', get_data_by_post, name='slug'),
]
When enter into home page, the home function in posts.views will generate some links with local data to render index.html.
def home(request):
final = get_local_suggest()
return render(request, "index.html", final)
Some of the code in index.html template likes below:
<a href="p/{{ results.code }}?From=homepage" class="portfolio-link" target="_blank">
So in home page , some links will show there: "http://example.com/p/code?From=homepage
But the tricky question here is that: when I click the url , the console of Django will print 301 like below. In browser, it will redirect from "/p/code" to "/p/code?From=homepage".
Not Found: /p/code [17/Apr/2017 15:05:23] "GET
/p/code?From=homepage HTTP/1.1" 301 0
There are must be something wrong with url pattern design, how to avoid it happened again?
Thanks!

Your url pattern ends with a slash, so your url should as well.
To make sure you always point your urls to the canonical url and avoid redirects, use the {% url %} template tag:
<a href="{% url 'posts:slug' results.code %}?From=homepage" class="portfolio-link" target="_blank">
Here 'slug' is the name of your url, and results.code is an argument to the url.

You can use request.GET.get('From', '') in your views, and clean your url pattern.

Related

Django doesn't load second page

I have just started Django, and I'm facing some difficulty.
When the first time I'm loading "localhost:8000/first_app" it is successfully loading index(), but on clicking on "About" link, url is changing to "localhost:8000/first_app/about/", but it is still loading "index()" and not "about()". Don't know what I'm missing.
Here's my project's URL:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^first_app/', include('first_app.urls')),
)
App's URL:
from django.conf.urls import patterns, url
from first_app import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/', views.index, name='about'),
)
And views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Rango says: Hello world! <br/> <a href='/first_app/about'>About</a>")
def about(request):
return HttpResponse("This is the ABOUT page! <br /> <a href='/first_app/'>Index</a>")
I'm using Django 1.7 and python 2.7.
Thanks.
You need to define your URLs like this;
urlpatterns = patterns('',
url(r'^about/$', views.about, name='about'),
url(r'^/$', views.index, name='index'),
)
Basically '^$' is the beginning & end of the match. The ^ is the start of the pattern & the $ is the end of the pattern so keep that in mind when defining your URLs. It's good practice to use $ to end your urls to avoid views being rendered regardless of what you add to the URL after what you match in your pattern.

Django Linking a html page to a view

So I know that there are other people who have asked the same question, and I have read through them. However, the solutions provided there are giving me a strange error, and I would appreciate any help in understanding it.
So here's my home.html file:
<head>
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
<!-- Sign Up -->
Sign Up
</body>
And here's my views.py:
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, "home.html")
def signup(request):
return render(request, "signup.html")
And here's my urls.py:
from django.conf.urls import url
from .views import home, signup
urlpatterns = [
url(r'^signup/', signup, name="signup"),
url(r'^', home, name="home"),
]
Thank you for all the help :)
Edit:
The error message is
Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name.
Also I actually changed the way I did urls.py. Now, I only have one urls.py in my main mysite folder:
from django.conf.urls import url, include
from django.contrib import admin
from home import views
from accounts import views as accountsViews
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^home/', views.home),
url(r'^signup', accountsViews.signup),
]
Your second url in 'urls.py' does not have a name.
The url tags would not be able to find them by name -- '{% url 'signup' %}'

Django URL in template NoReverseMatch

I keep getting a NoReverseMatch in my base template, though I've specified a namespace and have put the proper name.
Error:
Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['forum/|^forums/$']
Main urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from forum.views import main_home
urlpatterns = [
url(r'^$', main_home, name='home'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/|^account/', include('accounts.urls',
namespace='accounts')),
url(r'^forum/|^forums/', include('forum.urls', namespace='forum')),
]
Forum urls.py:
from django.conf.urls import url
from forum import views
urlpatterns = [
url(r'^$', views.home, name='home'),
]
From my template:
<a class="nav-link" href="{% url 'forum:home' %}">Forum</a>
The docs for reverse() say You cannot reverse url patterns that contain alternative choices using |.
In this case, you could change the URL to:
url(r'^forums?/', include('forum.urls', namespace='forum')),
However, it might be better to choice a single URL /forums/ or /forum/. Having a single URL can be better for SEO.

Django flaky url (randomly omits WSGIScriptAlias)

My Django site is producing URLs that intermittently omit my WSGIScriptAlias. If I simply print out {% url 'index' %} in my index.html (see my urls.py settings below) I randomly (around 50% of the time) get either:
MySiteAlias/MySite
which is correct, or
MySite/
which is incorrect.
myapp/urls.py:
from django.conf.urls import url,include
urlpatterns = [
url(r'^MySite/', include('mysite.urls')),
]
mysite/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
and views.index basically does return render(request, 'mysite/index.html). Any ideas on how to fix this?
I'd imagine you might have two urls with the same name, this is where namespaces will help. If you provide a namespace for your mysite.urls then there is no confusion on where you should go to
url(r'^MySite/', include('mysite.urls', namespace='mysite')),
{% url 'mysite:index' %}

Django Default main page functionality

i have installed DJANGO 1.5, once entered 127.0.01:8000 the beautiful HTLM page appears.
"it worked"
now whatever i enter in the Browser URL, it always goto default welcome page.
once i start playing with url.py this functionality get vanished. and i start getting 404 page.
is there any way to keep this functionality on i.e what ever is typed in the browser url it goes to main page exception for the defined url in url.py
please help
url.py
from django.conf.urls import patterns, include, url
from article.views import HelloTemplate
urlpatterns = patterns('',
url(r'^hello_template/$', 'article.views.hello_template'),
url(r'^hello_template_simple/$', 'article.views.hello_template_simple'),
other code snippet for "myproject/urls.py"
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^myapp/', include('myproject.myapp.urls')),
(r'^$', RedirectView.as_view(url='/myapp/list/')),
(r'', 'myproject.myapp.views'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Just put a your default page as a catch-all URL at the end of the other URLs:
urlpatterns = patterns('',
url(r'^hello_template_simple/$', 'article.views.hello_template_simple'),
url(r'', 'article.views.hello_template'),
Now any URL which isn't matched by hello_template_simple will be caught by hello_template.