Tuesday, March 1, 2016

Re: How force DJANGo choice MEDIA_URL or STATIC_URL in template?


I need choice base url MEDIA_URL (/media/) - for uploaded user picture, or STATIC_URL (/static/) - picture by default

I am try next:

p><img src="{% if account.accountuserinfo.picture %}MEDIA{% else %}STATIC{% endif %}_URL{{ account.accountuserinfo.picture_url }}" alt="picture_for_{{ account.name }}" id="account_picture"></p>

, but result is MEDIA_URL(STATIC_URL) and path to file.
 

You should work your {% if %} statement this way:

{% if account.accountuserinfo.picture %}
    <img src="{{ MEDIA_URL }}{{ account.accountuserinfo.picture }}">
{% else %}
    <img src="{{ STATIC_URL }}{{ account.accountuserinfo.picture_url }}">
{% endif %}

Trying to cram all of that together within the template is awful to read, and doesn't work as you've seen.

It would also make more sense to have the URL path of the default image set somewhere other than inside of a property. Either as a global variable for the model class, or even within your settings.py file and brought in as part of the template context if it can be used by other areas of the system. Querying an object instance for a static value like that is not good style.

-James

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciVZUn-Ks%3DeLQZKz-0aS%3DbrnkKNU3FOy4y7nBYzMmpfEpg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment