The 'cover' attribute has no file associated with it. Django - python

I want to display person pictures in a table with their name and surname columns. When i put as source static it show pictures but when i send request to database it didn't show. And its already insert data to database and picture to /media/images/.
view.py:
def viewpost(request):
person_list = Persona.objects.all()
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('surname') and request.POST.get('address'):
person = Persona()
person.name = request.POST.get('name')
person.surname = request.POST.get('surname')
person.address = request.POST.get('address')
person.age = request.POST.get('age')
person.cover = request.FILES['cover']
person.save()
return HttpResponseRedirect('/viewpost')
else:
return render(request, 'mysite/viewpost.html', {'persons': person_list})
model.py:
class Persona(models.Model):
name = models.CharField(max_length=255, unique=False)
surname = models.CharField(max_length=255, unique=False)
address = models.TextField()
age = models.CharField(max_length=255, unique=False)
cover = models.ImageField(upload_to='images/')
and template:
<td ><img src="{{person.cover.url}}" class="img-responsive" width="40px" id="pop" data-toggle="modal" data-target="#myModal"/></td>

Without having settings and template code it´s difficult to get the whole picture, but here you have some tips:
To show static files in a template remember to use the {% load static %} tag.
Anyway, user uploaded files live better in a media folder, not in static. You should include it in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

If problem is not solve. Try this.
in urls.py add this in bottom:
from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in html template
<form method="post" enctype="multipart/form-data">
in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

Related

how to read my files in template, django model filefield

I created two button for my pdf files, a button to read and one to download. my download button works but I don't know how to open the file with read button.
can I do as I did with the download button or is there a special method to open the files
models.py
class Books(models.Model):
author = models.ManyToManyField(Author)
title = models.CharField(max_length=250)
image = models.ImageField(upload_to='pics/cover/', default='pics/default-cover.jpg')
pdf_files = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf')
def __str__(self):
return self.title
forms.py
class BookForm(ModelForm):
class Meta:
model = Books
fields = '__all__'
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('book.urls')),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
detail.html
<div class="row">
<button class="btn btn-outline-success">Download</button>
<button class="btn btn-outline-primary">Read</button>
</div>
views.py
def detailView(request, id):
books = Books.objects.get(pk=id)
context = {
'books': books
}
return render(request, 'detail.html', context)
def addBooks(request):
form = BookForm()
if request.method == 'POST':
form = BookForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('allbooks')
context = {
'form': form
}
return render(request, 'books_form.html', context)
You can try that :
<embed src="{{ books.pdf_files.url }}" width="800px" height="2100px" />
I will display the PDF in your page.
For better readability you should create a new page with the PDF inside it
I found the solution, I uninstalled idm (Internet Download Manager) and my files open normally.
To download I just put download in front of href.
thankfor your answers
detail.html
<div class="row">
<a download href="{{ books.pdf_files.url }}"><button class="btn btn-outline-success">Download</button></a>
<button class="btn btn-outline-primary">Read</button>
</div>

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

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.

display uploaded files django

i have a problem with django. I need to display my files in single page
So i create model:
class UserProfile(models.Model):
profile_img = models.ImageField(upload_to='media/images/', blank=True, null=True)
profile_text = models.TextField()
profile_title = models.CharField(max_length=300)
profile_user = models.ForeignKey(User)
and form
class ProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = ['profile_img', 'profile_title']
then view
def cabinet(request):
form = ProfileForm(request.POST, request.FILES or None)
if request.method == 'POST' and form.is_valid():
obj = UserProfile(profile_img=request.FILES['profile_img'])
obj = form.save(commit=False)
obj.profile_user = request.user
obj.save()
return redirect(reverse(cabinet))
return render(request, 'cabinet.html', {'form': form})
I try use view
def user_page(request):
profile = UserProfile.objects.all()
return render(request, 'user_page.html', {'profile':profile})
and
{% for img in profile %}
{{ img.profile_img }}
{% endfor %}
it is not work
Help me plz, i try to read documentation but it doesn't help
So the code you pasted will only print path to your each profile.profile_img. And so is the profile_img attribute, it only stores a path to the image you uploaded, not the image itself. In order to use the media files uploaded to your website you need to specify a MEDIA_ROOT and MEDIA_URL in your settings.py.
Then you need to append it to your urls.py. You might want to look here also: show images in Django templates
After you have done so, to display an image in template just use HTML tag
<img src="{{MEDIA_URL}}{{ img.profile_img }}" />
I did it, as you said. Image doesn't display. I inspect element in browser: it should work
my settings:
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
And i have 2 urls, main file for my project:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^/cabinet', include('comments.urls') ),
url(r'^', include('user_login.urls')),]
and for my app:
urlpatterns = [
url(r'^$', views.cabinet, name='cabinet' ),
url(r'^/user_page/$', views.user_page, name='user_page'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I had the same problem, and i just def a str for my pic field to return the self.pic.url in the model itself, and in the template i just used {{pic}}.
Please correct this line
MEDIA_URL = '/media/' MIDIA_ROOT = os.path.join(BASE_DIR, 'media')
to
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
it should be MEDIA not MIDIA

Displaying images Django models

I am building my first website after finishing the how to tango with django tutorial and i am trying to add some images using the template language, but instead i get only little blue question mark icons
models.py
from django.db import models
class Galery(models.Model):
title = models.CharField(max_length = 120)
def __unicode__(self):
return self.title
class Image(models.Model):
galery = models.ForeignKey(Galery)
name = models.CharField(max_length = 50, unique = True)
picture = models.ImageField(upload_to='media')
description = models.CharField(max_length = 500)
materials = models.CharField(max_length = 150)
def __unicode__(self):
return self.name
galery.html
{%extends 'home/base.html'%}
{%load static%}
{%block body%}
<div class="col-lg-12">
<h1 class="page-header">My Projects</h1>
</div>
{%if image%}
{%for n in image%}
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="">
<img class="img-responsive" src="{% static 'media/{{n.image.url}}' %}">
</a>
</div>
{%endfor%}
{%endif%}
{%endblock%}
settings.py (part)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
MEDIA_ROOT = os.path.join(PROJECT_PATH,'media')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
STATICFILES_DIRS = (
STATIC_PATH,
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
EDIT: forgot to mention that i uploaded some images from the admin
EDIT2: in my urls.py i have
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
Django by default does not serve user-uploaded images. Set it up by adding the following URL conf:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is only for development. In production you will need to serve your files in a more scalable way (either directly from the HTTP server or even better, from a file storage service such as S3, or a CDN.)
For more info: https://docs.djangoproject.com/en/1.6/howto/static-files/#serving-files-uploaded-by-a-user-during-development

Categories

Resources