D
D
DmitryRise2017-05-02 15:09:57
Django
DmitryRise, 2017-05-02 15:09:57

How to master url magic in Django?

Hello, I recently started dipping into the back-end and started with Django (I poked around the tutorials, it worked, but there was a snag and understanding "why is it not working ?!" is not possible at the moment.
I create a view for the pages and specify them in controller.

def index(request):
    return render(request, 'blog/index.html')

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('blog.urls')),
    url(r'^post_list/', include('blog.urls')),
]

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$', views.post_list, name='post_list'),

]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

if settings.DEBUG:
    urlpatterns += [
        url(r'^images/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
    ]

I insert a link into the template
{% url "post_list" %}
When you click on the link, the url in the address bar changes, but the index template remains in its place. Tell me, please, what is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexandrBirukov, 2017-05-02
@DmitryRise

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'', include('blog.urls')),
    url(r'^post_list/', include('blog.urls')),
]

here url(r'^post_list/', include('blog.urls')) is removed, it makes no sense to include the same thing twice
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$', views.post_list, name='post_list'),
]

and here we make the second url unique, in general, the first match is searched, the rest are ignored

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question