Django display Image of User - python

Good Day,
every user has an image, how can I display the specific user image?
\\models.py
class UserImage(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE)
photo = models.ImageField(
upload_to='images/', height_field=None, width_field=None, max_length=100)
def __str__(self):
return str(self.user)
\\forms.py
class UserImageForm(forms.ModelForm):
class Meta:
model = UserImage
fields = (
'photo',
)
\\views.py
def photo_view(request):
try:
profile = request.user.userimage
except UserImage.DoesNotExist:
profile = UserImage(user=request.user)
if request.method == 'POST':
form = UserImageForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return redirect('/dashboard/user/photo')
else:
form = UserImageForm(instance=profile)
return render(request, 'photo.html', {'form': form, 'profile': profile})
test.html
<img src="{{ WhatHere? }}" alt="User Profile Image" />
So in src="" must be the URL to the image what the user has added. Each user can only see his own image, not all existing images should be displayed.
EDIT
\\settings.py
LOGIN_URL = '/signin'
LOGIN_REDIRECT_URL = '/signin'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
\\ urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from abstractuser.views import (
signup_view,
signin_view,
signout_view,
)
from dashboard.views import (
dashboard_home_view,
title_delete,
profile_view,
photo_view,
)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', signup_view),
path('signin/', signin_view),
path('signout/', signout_view),
path('dashboard/home', dashboard_home_view),
path('dashboard/title/delete/<int:title_id>',
title_delete, name="delete_title"),
path('dashboard/user/profile/', profile_view),
path('dashboard/user/photo/', photo_view),
]
I think I have to add something to the urls.py but I have no idea what

You can use
<img src="{{ profile.photo.url }}" alt="User Profile Image" />
And in your settings.py you have to set MEDIA_URL and MEDIA_ROOT AS
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
And in your project's main urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', signup_view),
path('signin/', signin_view),
path('signout/', signout_view),
path('dashboard/home', dashboard_home_view),
path('dashboard/title/delete/<int:title_id>',
title_delete, name="delete_title"),
path('dashboard/user/profile/', profile_view),
path('dashboard/user/photo/', photo_view),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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>

Imagefield in Django HTML Variable

I'm new to Django and trying to create a website with uploading image via Django Admin.
I'm trying to view image uploaded in Imagefield in my HTML.
But i just can't get the image working right.
Banner.objects.all() doesn't seems able to get all the image file located in media folder.
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.utils import timezone
from django.contrib.auth.models import User
from PIL import Image
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now) #auto_now=True //auto date
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Banner(models.Model):
title = models.CharField(max_length=100)
images = models.ImageField(upload_to='images',null=True,blank=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import(
ListView,
DetailView
)
from .models import *
# Create your views here.
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted'] #arrange date posted with latest on top
paginate_by = 6
def Banner_view(request):
banner = Banner.objects.all()
return render(request, 'blog/home.html',{'banner':banner})
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
#uploaded file in base directory "media"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
home.html
{% for b in banner %}
<div>
<img src="{{ b.images.url }}">
</div>
{% endfor %}
you should have write this way
you should use / for path detect
images = models.ImageField(upload_to='images/', null=True,blank=True)

images are not showing in django

hi when i am saving images from my admin they are saved in project directory like this images/images/myimg.jpg.. but when i am trying to display them in my template like this
<img src="{{About.image.url}}" alt="profile photo">
the image do not displays.. when i inspect the page in chrome... it shows image source unknown..
<img src="(unknown)" alt="profile photo">
please see the files ..
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'portfolio/static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'images')
project urls.py
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', include("home.urls")),
path('blog/', include("blog.urls")),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT )
the model having image is inside a app named 'home'
models.py of home app
from django.db import models
import datetime
# Create your models here.
class About(models.Model):
image = models.ImageField(upload_to = 'images')
desc = models.TextField()
home/views.py
from django.shortcuts import render
from home.models import *
from django.views.generic import ListView
# Create your views here.
def index(request):
abt = About.objects.all()
return render(request,'home/index.html',{'abt': abt.first()})
def Experience(request):
Exp = Experience.objects.all()
return render(request,'home/Experience.html',{'Exp': Exp})
class MyView(ListView):
context_object_name = 'name'
template_name = 'home/index.html'
queryset = About.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['Experience'] = Experience.objects.all()
context['Education'] = Education.objects.all()
context['Award'] = Award.objects.all()
context['Membership'] = Membership.objects.all()
context['About'] = self.queryset
return context
if about you're passing queryset so try looping them and accessing each image
{% for data in About %}
<img src="{{data.image.url}}" alt="profile photo">
{% endfor %}

DJANGO MEDIA_URL returns to same page instead of showing image

There are lots of answer on how to upload media files, what are the correct configuration and how to serve it on our application.
But my project seems to work nothing.
The aim is simple: User uploads an image. Django displays it on.
models.py
class UploadImageModel(models.Model):
image = models.FileField()
title = models.CharField(max_length=100, null=True, blank=True)
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include("Image.urls")),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render
from django.views import View
from .forms import UploadImageModelForm
from .models import UploadImageModel
# Create your views here.
class UploadImage(View):
def get(self, request, *args, **kwargs):
form = UploadImageModelForm()
context = {
"form":form,
}
return render(request, "index.html", context)
def post(self, request, *args, **kwargs):
form = UploadImageModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.title = str(instance.image)
instance.save()
context = {
"form":form,
"instance":instance,
}
return render(request, "index.html", context)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "Static")
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "Media")
index.html
{% if instance.image %}
<img src="{{instance.image.url}}" alt="Image"/>
{% endif %}
ERROR: After uploading an image named <something>.jpg, if I visit, 127.0.0.1:8000/media/1.jpeg, browser does not displays image, instead it shows index.html page.
SO how to serve this media file correctly?
This line is a catch-all for every URL:
url(r'', include("Image.urls")),
Without seeing the contents of Image/urls.py I can only suggest replacing that line with an explicit pattern that executes the index view, such as:
url(r'^$', my_index_view),

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

Categories

Resources