Error when trying to display a video in django - python

I'm trying to make a video display randomly on my homepage. A user is able to upload a video and it would be saved to a document in media/documents as well as to a dataset. I tried the code below and it keeps giving me an error,
Exception Type: TemplateSyntaxError at /
Exception Value: 'media' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_static
admin_urls
cache
i18n
l10n
log
static
staticfiles
tz
I removed if settings.DEBUG: from urls.py and added .url to {% media 'doc.document.url' %}, however this didn't work.
home.html
{% load media %}
{% for doc in document %}
<video width='320' height= '240' controls>
<source src="{% media 'doc.document.url' %}" type='video/mp4'>
Your browser does not support the video tag.
</video>
{% endfor %}
models.py
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from django.conf import settings
...
class Document(models.Model):
title = models.CharField(max_length=100, default='NoTitle')
description = models.CharField(max_length=255, blank=True)
document = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField("date published")#(auto_now_add=True)
creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path("", views.homepage, name="homepage"),
path("myconta/", views.myconta, name="myconta"),
path("upload/", views.model_form_upload, name="upload"),
path("register/", views.register, name="register"),
path('', include("django.contrib.auth.urls")),
]
#if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def homepage(request):
return render(request=request, template_name="main/home.html", context={"sites": Info.objects.all})
return render(request=request, template_name="main/home.html", context={"document": Document.objects.all})
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig',
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Directories
MySite
-main
-__pycache__
-migrations
-static
-images
main.css
-templates
[all my html code]
init
admin.py
apps.py
forms.py
models.py
tests.py
urls.py
views.py
-media
-documents
-mysite
-pycache
init.py
settings.py
urls.py
wsgi.py
db.sqlite3

home.html
{% load media %}
{% for doc in document %}
<video width='320' height= '240' controls>
<source src="{{ MEDIA_URL }} {{ doc.document.url }}" type='video/mp4'>
Your browser does not support the video tag.
</video>
{% endfor %}
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_PATH = os.path.join(BASE_DIR, '/media/')

Related

How to show model images in Django?

I have such models.py file
class Product(models.Model):
CATEGORIES = {
('Computer', 'Комп\'ютер'),
('Smartphone', 'Смартфон')
}
photo = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=5000, blank=False)
price = models.PositiveIntegerField(blank=False)
category = models.CharField(max_length=30, choices=CATEGORIES)
count = models.PositiveIntegerField(blank=False)
In settings.py i DON'T have media variables/dirs
Also i try to show images in such way
{% extends 'base.html' %}
{% block title %}Каталог{% endblock %}
{% block content %}
{% for i in products %}
<img src="{ static i.photo.url }">
{{i.title}}
{% endfor %}
{% endblock %}
Result:
I add my model objects in Django Admin
please see below configuration, have you done?
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# urls/path
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
your HTML file
{% if i.photo %}
<img src="{{ i.photo.url }}">
{% endif %}
You don't need the static tag.
<img src="{{ i.photo.url }}">
You can add like this.
and run the collectstatic command to
<img src="{% static '/logo.png' %}"/>
python manage.py collectstatic
In settings.py i DON'T have media variables/dirs
you have to set MEDIA_ROOT and MEDIA_URL in settings.py and set the URL of each in urls.py because by default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you’re using these defaults.
check the official doc.
step - 1
configure media and static files like this
add this in your settings.py
STATIC_ROOT = BASE_DIR / 'static_cdn'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
and add this in your urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Django Image should be displayed but isnt

I don't understand why the image isn't being displayed,
HTML
<div class="features-icons-item mx-auto mb-5 mb-lg-0 mb-lg-3">
<div class="features-icons-icon d-flex">
<img src="{{ x.pic.url }}">
</div>
model
class Item(models.Model):
title = models.CharField(max_length=200, default='item name...')
desc = models.TextField(default='Description....')
pic = models.ImageField(default='default.png', upload_to='item_pics')
views
def index(request):
itemList = Item.objects.all()
return render(request, 'main/items.html', {'itemlist': itemList})
settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I think you have not added the media url in urlpatterns.
Change the url.py in project as follows:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Refer the django documentation for more Explanations Django media files

I can't see ImageField's photos in DJango's view [Solve]

something fail in my Django project, because the images that I load in the imagefields don't show in the view.
https://www.dropbox.com/sh/fvx6sfmxgm08xo6/AABVR-AQGeF52pCxlzVaLuDaa?dl=0
The crab's photo it's load with "static", but the second, that it's imagefield's photo.
enter image description here
Model:
class foto(models.Model):
nombre=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='fotos/')
def __str__(self):
return self.nombre
View:
def general(request):
lista=foto.objects.all()
context={'material':lista}
return render(request,'indice.html',context)
settings:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
'/media/fotos/',
)
html:
{% load staticfiles %}
<html>
<head>
<title>Album de fotos</title>
</head>
<body>
<img src="{% static 'cangrejo.jpg' %}" />
{% if material %}
{% for a in material %}
<li>{{a.nombre}}: {{a.imagen}}</li>
<img src="{{a.imagen}}" />
{% endfor %}
{% else %}
<p>No hay fotos</p>
{% endif %}
</body>
</html>
Admin's URLS:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('colecion.urls')),
]
View's URLS:
from django.conf.urls import url, include
from colecion import views
urlpatterns =[
url(r'^$',views.general),
]
Edit: I already solve the problem!
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'ciencia/static')
models.py
foto=models.ImageField()
html
<img src="{% static alfa.foto %}" />
From the docs:
MEDIA_URL - "Absolute filesystem path to the directory that will hold user-uploaded files."
MEDIA_ROOT - "URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments."
Your current config's MEDIA_URL doesn't look right. It should be a URL, you have it set to a filesystem path. Try something like
MEDIA_URL = '/media/'
Add this to urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change {{a.imagen}} to {{a.imagen.url}}

Unable to display ImageField within Django template

I hope you can help me withmy Django project. I am able to upload an images under a media_cdn folder, inside a folder based on the name of the slug. The problem occurs when I try to display the image inside my post list and post.
Can you please have a look at my code and offer a solution. I spent hours trying to get it to work. Please help.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')
models.py
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
body = models.TextField()
date = models.DateTimeField()
updated = models.DateTimeField(auto_now=True)
postlist.html
{% block content %}
{% for post in posts %}
<div class="container w3-card-4">
{% if post.image %}
<img src="{{ post.instance.image.url }}">
{% endif %}
...
post.html
{% block content %}
<div class="row">
<div class="container w3-card-4">
{% if instance.image %}
<img src= "{{ instance.image.url }}" class="img-responsive">
{% endif %}
...
url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('personal.urls')),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I don't know what else to try to call that image from the folder. Any advice would be greatly appreciated. Thank you!
Use post.image.url instead of post.instance.image.url. Check the documentation.
ImageField inherits all the attributes of the FileField which includes url.

Django problems with media and image in template

Have a problem, try to do simple gallery in django, but when i tried to check how it looks, picture doesn't show anything only title name and there is at terminal "Error 404 not found". Can't realise what actually is wrong... Please help. thx...
Not Found: /media/images/example.png
[16/Mar/2016 17:59:17] "GET /media/images/example.png HTTP/1.1" 404 2168
models.py
class Album(models.Model):
title = models.CharField("Название альбома", max_length=100)
slug = models.SlugField("Ссылка на альбом", max_length=100, unique=True)
img = models.ImageField("Изображение альбома", upload_to='images',
help_text='Размер изображения 200px на 200px')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
class Photo(models.Model):
title = models.CharField("Название фотографии", max_length=100)
album = models.ForeignKey(Album, related_name='Альбом')
img = models.ImageField("Фото", upload_to='images',
help_text='Желательно не большой размер')
urls.py - app
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import ListView, DetailView
from .models import Album, Photo
urlpatterns = [
url(r'^$', ListView.as_view(
model=Album,
context_object_name='my_album',
template_name='gallery/album.html'),
name='gallery'
),
url(r'^(?P<slug>[-\w]+)/$', DetailView.as_view(
model=Album,
context_object_name='photos',
template_name='gallery/photo.html'),
name='photo'
),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
urls.py - project
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^gallery/', include('gallery.urls')),
]
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
template
{% extends "gallery/base.html" %}
{% load thumbnail %}
{% block title %}My Gallery{% endblock %}
{% block text %}
{% for album in my_album %}
<a href='{{ album.slug }}'>
<img src="{{ album.img.url}}" alt="{{ album.title }}">
<!-- {% thumbnail album.img "200x200" crop="center" as im %}
<img src="{{ im.url }}" alt="{{ im.title }}" width="{{ im.width }}"
height="{{ im.height }}">
{% endthumbnail %} -->
</a>
{% endfor %}
{% endblock %}
ProjectStructure
ProjectFolder/
app/
migrations/
static/
templates/
admin.py
models.py
..
project/
settings.py
urls.py
..
media/
images/
example.png
my_env/
manage.py
if in setting.py i do MEDIA_URL = 'media/images' it will work, but only for album template if you will go to see album photos, there photo won't shows too with the same error... Actually i can't understand and realise how to do access to folder media and just bring any of content placed here what i need. Help me...

Categories

Resources