Differences between get_media_prefix and media_url - django

What is the difference between them?
MEDIA_URL = 'media/'
link
link
They seem to work exactly the same, they create the same link.

You're correct. Both are same.
get_media_prefix is a templatetag provided by Django by making use of settings.MEDIA_URL. The django source code is given below:
def get_media_prefix(parser, token):
"""
Populate a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
"""
return PrefixNode.handle_token(parser, token, "MEDIA_URL")
The documentation states the same:
get_media_prefix populates a template variable with the media prefix
MEDIA_URL

Related

Custom tag not loaded in template

I've created a custom tag that I want to use, but Django can't seem to find it. My templatetags directory is set up like this:
pygmentize.py
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from django import template
from pygments.formatters.other import NullFormatter
register = template.Library()
#register.tag(name='code')
def do_code(parser,token):
code = token.split_contents()[-1]
nodelist = parser.parse(('endcode',))
parser.delete_first_token()
return CodeNode(code,nodelist)
class CodeNode(template.Node):
def __init__(self,lang,code):
self.lang = lang
self.nodelist = code
def render(self,context):
code = self.nodelist.render(context)
lexer = get_lexer_by_name('python')
return highlight(code,lexer,NullFormatter())
I am trying to use this tag to render code in gameprofile.html.
gameprofile.html
(% load pygmentize %}
{% block content %}
<title>{% block title %} | {{ game.title }}{% endblock %}</title>
<div id="gamecodecontainer">
{% code %}
{{game.code}}
{% endcode %}
</div>
{% endblock content %}
When I navigate to gameprofile.html, I get an error:
Invalid block tag on line 23: 'code', expected 'endblock'. Did you forget to register or load this tag?
For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
For other versions use static
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
Also you have to check that you defined STATIC_URL in setting.py
At last, make sure the static files exist in the defined folder
The error is in this line: (% load pygmentize %}, an invalid tag.
Change it to {% load pygmentize %}
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
in your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE.
did you try this
{% load games_tags %}
at the top instead of pygmentize?
{% load static %}
Please add this template tag on top of the HTML or base HTML file
Encountered this same issue but I just added {% load static %} from my extends template and it worked. So in your case if you're trying to load gameprofile.html from a base template you just need to add it like this:
{% extends 'some_base.html' %}
{% block content %}
{% load pygmentize %}
I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:
Create a new Django app by executing: python manage.py startapp new_app
Edit the settings.py file, adding the following to the list of INSTALLED_APPS: 'new_app',
Add a new module to the new_app package named new_app_tags.
In a Django HTML template, add the following to the top of the file, but after {% extends 'base_template_name.html' %}: {% load new_app_tags %}
In the new_app_tags module file, create a custom template tag (see below).
In the same Django HTML template, from step 4 above, use your shiney new custom tag like so: {% multiply_by_two | "5.0" %}
Celebrate!
Example from step 5 above:
from django import template
register = template.Library()
#register.simple_tag
def multiply_by_two(value):
return float(value) * 2.0
The app that contains the custom tags must be in INSTALLED_APPS. So Are you sure that your directory is in INSTALLED_APPS ?
From the documentation:
The app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work. This is a security feature: It allows you to host Python code for many template libraries on a single host machine without enabling access to all of them for every Django installation.
In gameprofile.html please change the tag {% endblock content %} to {% endblock %} then it works otherwise django will not load the endblock and give error.
You need to change:
{% endblock content %}
to
{% endblock %}

Using {% url 'view_name' object %} directly

The approach of doing {% url 'view_name' object.pk object.parent.slug %} isn't really flexible when switching to completety different url patterns. I'm looking for a way to do {% url 'view_name' object %} and to transcribe myself from object to object.pk and object.parent.slug in the url.
Like that
- template.html
{% url 'view_name' object %}
- urls.py [not real regex regex]
url('<object__parent__slug>/<object__pk>', views.view_name, name="view_name")
I know this is not at all possible with this syntax, but it's just to give an idea of what I'm looking for.
I will just add url methods inside my models:
class House(model.Models):
name = models.TextField()
....
def get_edit_url(self):
return reverse('view_name', {'pk':self.pk, 'name':self.name, 'owner_pk' : self.owner.pk })

How to pass variable in django but not as url parameter

I have this in urls.py:
urlpatterns = patterns('',
url(r'^add_to_cart/(?P<app_label>\w+)/(?P<model_name>\w+)/(?P<obj_id>\d+)/$', AddToCart.as_view(), name='add-to-cart'),
)
and i am using this to call AddToCart view in template:
{% for eg in eyeglasses %}
<p>{{eg}} <a href="{% url 'add-to-cart' eg|app_label eg|class_name eg.pk %}" >Buy</a> </p>
{% endfor %}
This ends up in having a url like this
"127.0.0.1/cart/add_to_cart/product/Sunglass/2/"
which i want to avoid. Is there any different way to pass these variables but without passing them as url parameters?
You can try passing them as querystring parameters instead of in url, so you can build url as
http://127.0.0.1/cart/add_to_cart?app_label=product&product=Sunglass&id=2
Build this in template as
{% for eg in eyeglasses %}
<p>{{eg}} <a href="{% url 'add-to-cart' %}?app_label={{eg.app_label}}&product={{eg.class_name}}&id={{eg.pk}} %}" >Buy</a> </p>
{% endfor %}
In view you can get it as
def add_cart_view(request):
....
product_name = request.GET.get('product')
...
Rather than having a list of links, create a form where you use buttons of type submit. For each button give it a value that you can retrieve from the request. When you submit the form set the method to post rather than get.
You may want to take a look part 4 of the Django tutorial.

Django 1.5: adminmedia and django-filebrowser-no-grappelli

I try to use django-filebrowser-no-grappelli with Django 1.5.
The prodlem is:
In Django 1.5 the template tags library adminmedia, which only contained the deprecated template tag {% admin_media_prefix %}, was removed.
Django-filebrowser-no-grappelli use adminmedia in templates:
{% adminmedia %}
<link rel="stylesheet" type="text/css" href="{% custom_admin_media_prefix %}css/forms.css" />
How can I fix it? Thx!
Ok,
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
.....
'django.core.context_processors.static',
)
Then change all {% adminmedia %} on {% static %}, {% custom_admin_media_prefix %} on {{ STATIC_URL }}.
Add quotes to all {% url 'someting' %} (new syntax in 1.5). Maybe it's not absolutely correct, but it's working.
But, I can't add filebrowser to the TinyMCE :( Why?
See, {% url %} tag had some disadvantage in syntax: when you typing {% url app.views.view %} it can be read in two ways:
You have your view function in app.views
You have variable or object 'app' with method or key or property called 'views' and 'view' inside it.
It was ambiguous so since django 1.5 you should define your view location like a string:
{% url 'app.views.view' %}.
BTW, i think there is no fork of django-filebrowser-no-grappelli with support django 1.5. I hope it will be soon

Django - Custom inclusion template tag MEDIA_URL?

I have the following custom inclusion tag:
from django.template import Library
from django.db.models import Count
register = Library()
#register.inclusion_tag('projects/work_part.html', takes_context=True)
def project_list(context):
return {'projects':context['projects']}
My settings look like this:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'context_processors.default_processors',
)
I need to access MEDIA_URL within the work_path.html template but it seems the context processors are not applied to custom templates.
How do I access MEDIA_URL within my template tag? I saw this post: Access STATIC_URL from within a custom inclusion template tag but I am not using STATIC_URL, is there another set of tags I should be loading?
The get_media_prefix tag is in static for those of us that were looking to "load media"...
{% load static %}
...
<img class="img" src="{% get_media_prefix %}{{ obj.image }}" alt="{{ obj.name }}" />
You can do the same (as with STATIC_URL) using the tempatetag {% get_media_prefix %}
Or you can just ignore those template tag and use MEDIA_URL variable right away. All of the variables from settings.py are accessible from the template HTML.
<img class="img" src="{{ MEDIA_URL }}{{ obj.image }}" alt="{{ obj.name }}" />