Best way of linking to a page in Django - python

I managed to create a URL tag for my index. But right now I'm confused how to add links to other pages.
I put this on my urls.py
url(r'^$', 'index', name='index'),
The next thing I put this tag into the href:
{% url 'index' %}
But what if I wanted to create a new page and would be linking to it. How would I do it the best way?

So next you would extend your urls.py to look something like this:
url(r'^$', 'index', name='index'),
url(r'^blog$', 'blog', name='blog'),
Then in your html you can use either one:
Home
Blog
You can of course use the template tage {% url 'index' %} as many times as you need in any template.

Django has updated urlpatterns to take 'path' instead of using url so it's become much more efficient. You don't have to use regex anymore
from django.urls import path
from . import views
urlpatterns=[
path('', views.index , name='index'),
path('blog/', views.blog , name='blog'),]
Then in templates, you can use template tagging
Index
Blog
If you have multiple apps, you can tag it as follows. For example, if this is under 'post' app:
In post app urls.py:
from django.urls import path
from . import views
app_name = 'post'
urlpatterns=[
path('', views.index , name='index'),
path('blog/', views.blog , name='blog'),]
in the project urls.py:
from django.urls import path, include
urlpatterns=[
path('post/', include('post.urls'),]
In templates, you do as following:
Index
Blog

Just use the same label {% url 'index' %}.
You may use each name in urls.py to link to the url.
urls.py
url(r'^archive/$', 'mysite.views.archive',name='archive'),
url(r'^about/$', 'mysite.views.about',name='about'),
url(r'^contact/$', 'mysite.views.contact',name='contact'),
template
About
Contact
If you have many apps, use namespace
https://docs.djangoproject.com/en/dev/topics/http/urls/#url-namespaces-and-included-urlconfs

Use the below syntax:
<a href="{% url 'cart' %}" > Cart page </a>
Where URL 'cart' is the name field in your app URL pattern.
urlpatterns = [
#Leave as empty string for base url
path('', views.shop, name="store"),
path('cart/', views.cart, name="cart"),--------------------->
path('checkout/', views.checkout, name="checkout"),
path('shop/',views.shop, name="shop"),
]

Create a new URL in the same format and give that name instead of index.
Eg:
url(r'^$', 'index', name='index'),
url(r'^new/page/$', 'new', name='new_page'),
{% url 'new_page' %}

Example:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about', name='about'),
)
Now, in the html template rendered by your views.index you can have:
about

Related

Supposed simple Django slug categories, but I get a 404 and I can't figure out why

thanks for taking a moment to try and help me out. Haven't done much coding in many years, switched careers for some reason.. Decided to play with Django, everything was going fine, and I can't figure out this URL/slug problem. I've got some links, first.
It's explained on their GitHub rep but I can't figure it out. I've also used this handy site and am still in the dark.
I Know its relatively simple, just having a hard time finding up to date code and books, and I've been frustrating myself on it for too long to quit. It's got to be an error with my URL's, I just don't know what though. So, have a laugh at my expense (seriously, you should have heard Linode support when I logged into the wrong account and deleted the wrong server.. they have excellent support!) and help me amuse myself a bit through this pandemic, because I'm mostly playing with stufff as part of a bigger project I started a while before I quit computer science and went into welding..
Basically, add a page to a category. Better looking URL's with slugs, no problem, until I try to access outside of /admin with the slug. I've basically got it text for text, and am getting this:
Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order:
404
[name='index']
rango/
admin/
category/slug:category_name_slug/ [name='category']
^media/(?P.*)$
The current path, category/useless/, didn't match any of these.
I get that when I try to access localhost/rango/category/category-name-slug, or localhost/category/category-name-slug
Here is my project urls.py
from django.contrib import admin
from django.urls import path
from django.urls import include
from django.conf import settings
from django.conf.urls.static import static
from rango import views
urlpatterns = [
path('', views.index, name='index'),
path('rango/', include('rango.urls')),
path('admin/', admin.site.urls),
path('category/slug:category_name_slug/', views.category, name='category'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And this is from my app urls.py
from django.urls import path
from rango import views
app_name='rango'
urlpatterns = [
path('', views.index, name='index'),
path('category/slug:category_name_slug/', views.category, name='category'),
]
And a snippet from my index.html file, because I can't get category.html to load anywhere without a 404, I can get the slug name to show up beside the category name, if you're wondering what on earth I'm doing.
{% if categories %}
<ul>
{% for category in categories %}
<li>;{{ category.name }} {{ category.slug }};
</li>
{% endfor %}
</ul>
{% else %}
{% endif %}
and last, my app's views.py
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
def index(request):
category_list = Category.objects.order_by( '-likes' )[:50]
context_dict = { 'categories': category_list }
return render(request, 'rango/index.html', context_dict)
def category(request, category_name_slug):
context_dict = {}
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
return render(request, 'rango/category.html', context_dict)
I get that when I try to access localhost/rango/category/category-name-slug, or localhost/category/category-name-slug
There is a rendering problem with the Markdown file. If you inspect the raw version [GitHub], you see the real urlpatterns. This needs to use angle brackets (<…>), so:
urlpatterns = [
path('', views.index, name='index'),
path('rango/', include('rango.urls')),
path('admin/', admin.site.urls),
path('category/<slug:category_name_slug>/', views.category, name='category'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#SanZo- Why are you adding the following urlpattern at two places.
path('category/slug:category_name_slug/', views.category, name='category'),
It should only be inside your app (rango).
I don't understand why you would try this.rango/ admin/ category/slug:category_name_slug/
The simplest thing to do is - if you want to access the category_slug view
then do this 127.0.0.1:8000/rango/category/{slug}/
e.g 127.0.0.1/rango/category/pillow/

How to fix 'str' object is not callable in django

Hi Everyone I made A Blog but when i delete post i get this error i'm using django latest version:
TypeError at /post/(?P3\d+)/remove/
'str' object is not callable'
Here Is My Views.py
class PostDeleteView(LoginRequiredMixin,DeleteView):
success_url = reverse_lazy('post_list')
model = Post
Here is my app Urls.py
from django.urls import path
from blog import views
urlpatterns = [
path('',views.PostListView.as_view(),name='post_list'),
path('about/',views.AboutView.as_view(),name='about'),
path('register/',views.user_register,name='user_register'),
path('post/(?P<pk>\d+)',views.PostDetailView.as_view(),name='post_detail'),
path('post/new/',views.CreatePostView.as_view(),name='post_new'),
path('post/(?P<pk>\d+)/edit/',views.PostUpdateView.as_view(),name='post_edit'),
path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'),
path('drafts/',views.PostDraftListView.as_view(),name='post_draft_list'),
path('post/(?P<pk>\d+)/comment/',views.add_comment_to_post,name='add_comment_to_post'),
path('comment/(?P<pk>\d+)/approve/',views.comment_approve,name='comment_approve'),
path('comment/(?P<pk>\d+)/remove/',views.comment_remove,name='comment_remove'),
path('post/(?P<pk>\d+)/publish/',views.post_publish,name='post_publish'),
]
Image
https://i.stack.imgur.com/wbcfn.png
Here is my post_confirm_delete.html
{% extends "blog/base.html" %}
{% block content %}
<form method="POST">
{% csrf_token %}
<p>Are You sure you want to delete {{ object }}?</p>
<input type="submit" class="btn btn-danger" value="Confirm">
</form>
{% endblock %}
Here is my Project Urls.py
"""blogpro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
from django.contrib.auth.views import LoginView,LogoutView
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('accounts/login/', LoginView.as_view(), name='login'),
path('accounts/logout/', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
]
You are using path with regex which is not how it work docs, only use regex url string with re_path
it should be :
path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'),

How to properly get url for the login view in template?

I have a small problem with figuring out how {% url 'something' %} works in django templates.
When I run my website in debug mode, I see this in stdout:
web_1 | [21/Dec/2015 11:29:45] "GET /accounts/profile HTTP/1.1" 302 0
web_1 | /usr/local/lib/python3.5/site-packages/django/template/defaulttags.py:499: RemovedInDjango110Warning: Reversing by dotted path is deprecated (django.contrib.auth.views.login).
web_1 | url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
web_1 |
The /accounts/profile maps to a template, and the only place in this template that mentions django.contrib.auth.views.login is the following:
Log out
So, I guess that for some reason this is not the proper way to use {% url %} command. What is the proper way? How to get rid of this warning?
Here are my urlpatterns:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^accounts/profile', views.profile_view),
url(r'^$', RedirectView.as_view(url=reverse_lazy(views.profile_view)))
]
You should use the name of the url, instead of its dotted path.
In this case, you have included the url patterns from django.contrib.auth.urls. If you look at that urls file, you can see that the name of the views are login and logout.
urlpatterns = [
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
...
]
Therefore, change your link to:
Log out
Have a look at
urls.py
url(r'^login/$', views.login, name='login'),
you can refer the name when using url
{% url 'login' %}
and
{% url 'logout' %}
or if you need to logout with next then
Logout
Check out this post
'django.contrib.auth.views.login'
In urls.py add the name to each relevant entry (not the the ones which include other definitions, as the name would be ignored)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^accounts/profile', views.profile_view, name='acc_profile'),
url(r'^$', RedirectView.as_view(url=reverse_lazy(views.profile_view)), name='home')
]
Then in the templates use the name of the url entry, as defined above i.e.
The link text
In the given case, the login and logout urls come from the standard django.contrib.auth.urls and their name is simple enough (see here for further info)
Log out

How to deal with my login_required url?

I have:
Linker urls:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$',
include('distributors.urls', namespace='distributors')),
url(r'^accounts/', include('allauth.urls')),
]
App urls:
url(r'^$', views.Index.as_view(), name='index'),
url(r'^links/$', login_required(views.LinkListView.as_view(), name='links'),
in my html i have href="{% url 'distributors:index' %}" and href="{% url 'distributors:links' %}"
Views:
class Index(TemplateView):
template_name = "distributors/index.html"
class LinkListView(ListView):
model = Link
template_name = "distributors/links.html"
context_object_name = 'links'
When I try to enter http://127.0.0.1:8000/ I see The included urlconf 'linker.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
Any ideas how to fix this?
Firstly remove the dollar sign when including other url patterns.
url(r'^',
include('distributors.urls', namespace='distributors')),
Secondly, you are missing a closing bracket where you are using login_required.
url(r'^links/$', login_required(views.LinkListView.as_view()), name='links'),

django-registration - NoReverseMatch at /accounts/login/at /accounts/login/

Trying to make django-registration work within the Django Tutorial polls projects.
I'm using Django 1.6, django-registration 1.0 and the django-registration-templates
When I try to access
http://localhost:8000/accounts/login/
I get
NoReverseMatch at /accounts/login/
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
The line in the template, mysite/templates/base.html, that's cited in the error report is :
{% trans "Home" %} |
And I do have a url with name 'index' in my polls.url :
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
So I feel like that should work ? Help ?
EDIT 1
polls.urls:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
mysite.urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls')),
)
registration.urls:
"""
Backwards-compatible URLconf for existing django-registration
installs; this allows the standard ``include('registration.urls')`` to
continue working, but that usage is deprecated and will be removed for
django-registration 1.0. For new installs, use
``include('registration.backends.default.urls')``.
"""
import warnings
warnings.warn("include('registration.urls') is deprecated; use include('registration.backends.default.urls') instead.",
DeprecationWarning)
from registration.backends.default.urls import *
OK I've figured out the problem here. The url with name 'index' was defined in polls.urls and so within the template I needed to change :
{% trans "Home" %}
to
{% trans "Home" %}
As mentioned in the Django 1.6 documention of the url tag and which I quote here for convenience :
If you’d like to retrieve a namespaced URL, specify the fully
qualified name:
{% url 'myapp:view-name' %}
This will follow the normal namespaced URL resolution strategy,
including using any hints provided by the context as to the current
application.

Categories

Resources