I'm new to Django so this could be a stupid question, however I'm struggling to find an answer searching Goolge. my question is as follows...
In other languages when creating links within HTML pages you have something like a buildURL(page) function that creates a dynamic link i.e.
<a herf="buildURL(pageName,queryObjects) >link</a>
This would generate the URL with parameters.
Is there a function in Django that builds URLs in the correct format i.e. generate a fully-qualified URL to a Django page with parameters?
In your templates, you never should hard write url view. Instead of this, a good practice is to named each url and reference this name in templates.
To name a url:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
#...
url(r'^article/(\d+)/$', 'news.views.article', name='article_by_id'),
#...
)
To reference url in template:
<ul>
{% for article in articles %}
<li>Article {{article.name}} </li>
{% endfor %}
</ul>
Learn more in URL Distpatchar django documentation.
from what I see in the django documentation it should be
<ul>
{% for article in articles %}
<li>Article {{article.name}} </li>
{% endfor %}
</ul>
i.e. 'article_by_id' instead of article_by_id. This works for me
Related
I am making my own portfolio website using Django.. So the idea is: Make posts containing websites that i've developed. All these posts will be displayed in a page called "Projects" and then you can access a single project to read about it. Every project i upload have an ID, so i used this code to acess each project page:
# Single project page
path('projects/<int:post_id>/', views.project, name='project'),
Then in my PROJECTS page i have a simple(for now) HTML code to show all my projects and link them to the single project page. What i want to know is how to LINK this ID generated URL in this code:
<ul>
{% for project in projects %}
<li>{{ project }}</li>
{% empty %}
<li>No project have been added yet.</li>
{% endfor %}
</ul>
I tried using:
<li><a href="{% url 'main_portfolio/projects/<int:post_id>/' %}</a></li
And some other things but nothing i try is working.
Maybe try <a href="{{ project.get_absolute_url }}">, or
<a href="projects/{{ project.id }}/">
You can work with the {% url … %} template tag [Django-doc]:
<li>some text</li>
I'm a beginner in django-oscar and I try to manage a new view on the page.
I've already created two pages with django-oscar dashboard,
https://ibb.co/cM9r0v
and made new buttons in the templates:
Lib/site-packages/oscar/templates/oscar/partials/nav_primary.html
https://gist.github.com/Kalinar/076fc8144869c3b50fc0bc9e52f825e4
I have no idea how to make a good a href="???" to new pages in buttons ... can someone help?
Maybe there is better way to do it, can you explain it to me?
Oscar uses Django's flatpages app, so you can use their template tags to dynamically add in navigation links to the pages you create.
{% load flatpages %}
{% get_flatpages as flatpages %}
{% for page in flatpages %}
<li class="dropdown active">
<a href="{{ page.url }}" class="dropdown-toggle" {% if not expand_dropdown %} data-toggle="dropdown"{% endif %}>
{% trans page.title %}
</a>
</li>
{% endfor %}
You can find more information on the flatpages app in the Django flatpage documentation.
You already know the title and of course the id of the page, and each page is an instance of the model PagePromotion, just query the model for such name/id and use the attribute page_url of the returned instance to send it within a variable in the context of the view that renders the menu.
Then in the template:
href="{{ variable_containing_url }}"
I am using Django and developing an i18n site serving many languages. I want to make a modal that stays in base.html, so that users can switch the language wherever they are.
I managed to do something like this.
<div class="modal-body">
{% get_available_languages as languages %}
{% for lang_code, lang_name in languages %}
{% language lang_code %}
{{lang_code|lang_name}}
{% endlanguage %}
{% endfor %}
</div>
Which turns out urls like:/ja/, /en/, /fr/, etc..
but this kind of approach links to the main page only.
When using {{request.path}} or {{request.get_full_path}} for the url like:
{{lang_code|lang_name}}
It doesn't include the i18n url patterns..
Is there any way for directing current url with request.path??
TARGET
When in /foo/ : /ja/foo/ /en/foo/ /fr/foo/
When in /bar/ : /ja/bar/ /en/bar/ /fr/bar/
Thanks in advance!
This topic is discussed in this SO question: Django templates: Get current URL in another language.
In my project, I use this simple template tag (taken from https://djangosnippets.org/snippets/2875/), which returns the URL of the current view in another language.
foo/templatetags/i18n_urls.py:
from django import template
from django.urls import translate_url
register = template.Library()
#register.simple_tag(takes_context=True)
def change_lang(context, lang: str, *args, **kwargs):
path = context['request'].path
return translate_url(path, lang)
some_template.html:
{% load i18n_urls %}
<ul>
<li>
EN
</li>
<li>
CS
</li>
<li>
DE
</li>
</ul>
Please note that translate_url function is not documented in the official Django docs. Here is the source code of this function: https://github.com/django/django/blob/master/django/urls/base.py#L161-L181.
Can someone show me an example (plus a small explanation) of how {% load url from future %} and namespace concept works?
I'm new in python and django and i need to learn how not to make hardcoded urls and also how to use other functions like reverse().
Here is an example of what i'm trying to do:
urls.py
urlpatterns = patterns('',
"""
This one is what i did first but works with hardcoded url inside
top-navigator.html:
url(r'^books/$', 'books.views.book_index'),
The next one is what i'm trying to do:
(but of course is not correct)
"""
url(r'^books/$', include('books.views.book_index', namespace='books')),
)
top-navigator.html
when i'm trying to run the server is shows the error:
Caught ImportError while rendering: No module named book_index
{% load url from future %}
<div class="navbar-inner">
<ul class="nav">
<li class="active">Home</li>
<li>Books</li>
<li>Authors</li>
<li>Publishers</li>
<li>Contact</li>
</ul>
</div>
What can i do in order do to something similar for all the links?
Thanks in advance.
To use namespaces and the include statement, you must import another urls.py file with patterns in it.
You can't just include a view as you've done here.
Change your code to
{% url 'book_index' %}"
url(r'^books/$', 'books.views.book_index', name='books'))
Or to use namespaces for illustration purposes:
more_patterns = patterns('',
url(r'^$', 'book.views.book_index', name='book_index')),
)
urlpatterns = patterns('',
url(r'^books/', include(more_patterns, namespace='books')),
#^^^^^^^ note you would normally use a string that points
# to a python file containing urls.
)
{% url 'books:book_index' %} will now resolve.
I want to have SEO-friendly URL,my current url in urls.py :
(ur'^company/news/(?P<news_title>.*)/(?P<news_id>\d+)/$','CompanyHub.views.getNews')
I use it in template:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews n.title,n.pk %}" >{{n.description}}</a>
{% endfor %}
I use news_id to get news object with that PK .
I want to convert this url:
../company/news/tile of news,with comma/11
to:
../company/news/tile-of-news-with-comma/11
by doing some thing like this in template:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews slugify(n.title),n.pk %}" >{{n.description}}</a>
{% endfor %}
I checked out these questions:
question1
question2
question3 and this article but they save an slugify field in database while I wanna generate it on demand.in addition I want to run a query by news_id.
I think this question is good,but I don't know how to use news_id to fetch my news object
This will generate the needed url:
{% for n in news %}
<a href="{% url CompanyHub.views.getNews n.title|slugify n.pk %}" >{{n.description}}</a>
{% endfor %}
The examples above save slugify_field in database, as they later search for it. Otherwise in database you'll have a normal title, and slugified title in code for searching.. No easy way to compare them. But the way you've explained is simpler. You will have this kind of view:
def news(request, slug, news_id):
news = News.objects.filter(pk=news_id)
UPDATE: To use unicode symbols in slugify, you'll need a conversion first. Look at this: How to make Django slugify work properly with Unicode strings?. It uses the Unidecode library
Then add a custom filter:
from unidecode import unidecode
from django.template.defaultfilters import slugify
def slug(value):
return slugify(unidecode(value))
register.filter('slug', slug)
then in your template use this:
{% load mytags %}
<a href="{% url CompanyHub.views.getNews n.title|slug n.pk %}
Here is an example:
{{ "影師嗎 1 2 3"|slug}}
renders as:
ying-shi-ma-1-2-3
Have you tried n.title|slugify and see if that works for you.
ref: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#slugify
Note: although this is possible, just make sure the 'slugified' element is never used for any part of routing... (ie, purely for display only)