0

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!

Tony Wang
  • 971
  • 4
  • 16
  • 33

2 Answers2

1

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.

knbk
  • 52,111
  • 9
  • 124
  • 122
  • Thanks for your reply. In this case, "slug" seems doesn't work. Error during template rendering In template /home/ubuntu/workspace/templates/index.html, error at line 50 Reverse for 'slug' with arguments '(u'BI3nsz4BBnV',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] – Tony Wang Apr 17 '17 at 16:37
  • 1
    @TonyWang Right, I missed the namespace. Try `'posts:slug'` instead. – knbk Apr 17 '17 at 16:44
0

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

XaviP
  • 188
  • 1
  • 2
  • 8