I'm trying to show all the image correlated to a chapter.
I cannot figure out what is wrong, base on what I found online it should work, but no images are display.
Only the outer div is coming out on html source.
By debugging the template I also notice that the for loop is taking all the chapters in the DB, not only the chapter I selected.
I think I need to restrict the ChapDetail view query somehow.
Can someone advise me on this two issue?
model.py
def image_dir_path(instance, filename):
book = instance.chap.book.slug
chapter = instance.chap.slug
return os.path.join(book, chapter, str(uuid.uuid4().hex))
class Chapter(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
default=settings.AUTH_USER_MODEL
)
book = models.ForeignKey(
Book,
related_name='chapters',
on_delete=models.CASCADE,
default=''
)
title = models.CharField(max_length=130, unique=True)
slug = models.SlugField(max_length=150, blank=True)
created_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('chap_detail')
class ShowImages(models.Model):
chapter =models.ForeignKey(
Chapter,
on_delete=models.CASCADE,
default='',
related_name="pics"
)
picture = models.FileField(upload_to=image_dir_path, default='')
def __str__(self):
return self.picture.name
view.py
class ChapDetail(generic.ListView):
model = Chapter
template_name = 'chapters/chapter_detail.html'
urls.py
app_name = 'chapters'
urlpatterns = [
path('<str:book>', views.BookChaps.as_view(), name='chap_list'),
path('<str:book>/<str:slug>/', views.ChapDetail.as_view(), name='chap_detail'), # both slug fields
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
template
<div style="padding-top: 10px; display: block;">
{% for i in chapter.picture_set.all %}
<div>
<img src="{{ i.picture.url }}" alt="Not found">
</div>
{% endfor %}
</div>
media folder:
For restricting you query you can use the methode .filter() Filter Django Docs
It would be something along the line Chapter.objects.filter(id=id).
You can get the id (or other filter param) from you path params in the url.
For the missing pictures, are you sure your MEDIA URL is set correct in the settings?
Related
I have model named Book in models.py file.
And based on this model, a view has been created to display images as products.
Which renders books(products) on shop.html template.
Problem is that i am unable to get their cover images which are saved across each publishers id who is seller of those books.
This is code of shop.html (in which i am trying to display image).
<div class="container mt-4">
<div class="row">
{% for b in books|slice:":10" %}
<div class="col-lg-2 col-md-3 col-sm-4">
<div class="book-card">
<div class="book-card__book-front">
<img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image">
</div>
</div>
<div class="book-card__title">
{{ b.title }}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
This is the model in which i am putting covers of books against publisher's ids (names)
def book_cover_path(instance, filename):
return os.path.join(
"covers", instance.publisher.user.username, str(
instance.pk) + '.' + filename.split('.')[-1]
)
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField('Title', max_length=255)
authors = models.ManyToManyField(Author, related_name='books_written')
publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published')
price = models.DecimalField('Price', decimal_places=2, max_digits=10)
description = models.TextField('Description')
upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True)
categories = models.ManyToManyField(Category, related_name='book_category')
cover = models.ImageField(upload_to=book_cover_path, null=True,blank=True)
class Meta:
unique_together = ('title', 'publisher')
get_latest_by = '-upload_timestamp'
This is view in views.py
def shop(req):
bookz = Book.objects.order_by('title')
var = {'books': bookz, 'range': 10}
return render(req, 'bookrepo/shop.html', context=var)
This is media setting in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
This is my folder structure i did put covers in media/covers/publisher/image.jpg EVEN i tried something like this media/media/covers/publisher/image.jpg
This is structure of media directory
I am getting NOT FOUND error in django console
Not found error like these
I think this have to do something with url i m trying to create must be missing something.
Otherwise b.title is working fine. Issue is just with image retrieval.
IF anyone don't understand book_cover_path function they can just tell me the way to make url as if books are lying in media/covers/image.jpg because i am unable to do this ALSO. As,
cover = models.ImageField(upload_to='covers', null=True,blank=True)
replace this line
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
to
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
because it is the Absolute path to the directory that will hold the file.
and replace
<img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image">
to
<img src="{{b.cover.url}}" alt="book-image">
and add these lines in projects url.py file
from django.conf import settings
from django.conf. urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
try this on shop.html ,Check the docs here.
<img src="{{ b.cover.url }}" alt="book-image">
I'm new to Django and sorry if the question is silly. I have a URL with two slugs, one for the category which is a manytomany field and one for the posts:
path('<slug:slug_staticpage>/<slug:slug>/', views.post, name='post_detail')
views.py
def post(request, slug, slug_staticpage):
category = get_object_or_404(StaticPage, slug_staticpage=slug_staticpage)
blogpost = get_object_or_404(Post, slug=slug)
post = Post.objects.filter(slug=slug)
page_id = category.pk
related_posts = Post.objects.filter(static_page__pk=page_id)[:6]
return render(request, "blog/blog-post-final.html", {'slug': slug, 'slug_staticpage': category.slug_staticpage, 'post':post, 'related_posts':related_posts})
models.py
class Post(models.Model):
title = models.CharField(max_length=300)
content = RichTextField()
slug = models.SlugField(max_length=200, unique=True)
published = models.DateTimeField(verbose_name="Published", default=now())
image = models.ImageField(verbose_name="Image", upload_to="blog", null=True, blank=True)
author = models.ForeignKey(User, verbose_name="Author", on_delete=models.PROTECT)
categories = models.ManyToManyField(Category, verbose_name="Categories", related_name="get_post")
static_page = models.ManyToManyField(StaticPage, verbose_name="Página estática", related_name="get_post")
created = models.DateField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.IntegerField(choices=STATUS, default=0)
I want to display those URLs in my homepage via the template tag, but I don't know how to retrieve the slug_staticpage slug:
<a href="{% url 'blog:post_detail' slug_staticpage=post.slug_staticpage slug=post.slug %}">
The above syntax is not working, I can only retrieve the slug of the post.
Can someone help me sort this out? Thanks a lot for your precious help :)
Askew
As you have a Many-to-Many relationship, you should have a single url for each of those static_page objects.
You can achieve that via iterating over the static_page objects:
{% for slug_url in post.slug_staticpage.all %}
<a href="{% url 'blog:post_detail' slug_staticpage=slug_url slug=post.slug %}">
{% endfor %}
although I'm not sure whether you really need such relationship or not.
I solved it myself by adding the following to models.py
def get_absolute_url(self):
return reverse('blog:post_detail', kwargs={'slug_staticpage':self.static_page.slug_staticpage, 'slug':self.slug})
Cheers!
I am trying to display images into articles in my blog project built with Django. Here is the related code:
settings.py:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"
urls.py (project):
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py:
class Article(models.Model):
title = models.CharField(max_length=150)
slug = models.SlugField(max_length=150)
author = models.CharField(max_length=80)
text = models.TextField(null=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False,
verbose_name="Date de parution")
image1 = models.ImageField()
image2 = models.ImageField()
image3 = models.ImageField()
def __str__(self):
return self.titre
views.py:
def article(request, id, slug):
article = get_object_or_404(Article, id=id, slug=slug)
return render(request, 'blog/post.html', {'article': article})
post.html:
<img src="{{ article.image1.url }}"/>
<img src="{{ article.image2.url }}"/>
<img src="{{ article.image3.url }}"/>
However, it does not work. Images do not appear. Any suggestions ?
There shouldn't be any forward slashes before or after media, it should simply be .join(BASE_DIR, 'media'). also you don't need to add upload_to('media') because the root is media. You are not advised to add images in media root, you should create an img folder inside media folder, and then add upload_to('img/') in your imagefield.
Regarding inserting image preview inside a textbox/textfield, yes it is possible, but it should be a separate question, although I think there are many identical questions on it.
I am trying to make a blog with an imagefield for my posts. I have imageupload working in the django admin panel but I have broken thumbnails. If I click on the images I got a 404 error with the following:
Using the URLconf defined in firstblog.urls, Django tried these URL patterns, in this order:
^$ [name='home']
^admin/
The current URL, images/heroimage/, didn't match any of these.
in my models.py I have:
from django.db import models
from django.db.models import permalink
class posts(models.Model):
author = models.CharField(max_length = 45)
title = models.CharField(max_length = 100)
bodytext = models.TextField()
timestamp = models.DateTimeField()
image1 = models.ImageField(upload_to="images/heroimage/", default='')
category = models.ForeignKey('blog.Category', default='')
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_post', None, { 'slug': self.slug })
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_blog_category', None, { 'slug': self.slug })
What I'm trying to do is to have the image that was uploaded to the post, displayed on the site.
Here is my index.html where I try to call the image to the post.
<div class="container">
<h1>First Blog</h1>
{% for post in posts %}
<div class="posts">
<p> <img src="{{blog.image1.url}}" /> {{ blog }}</p>
<h2>{{ post.title }}</h2>
<h3>Posted on {{ post.timestamp }} by {{ post.author }}</h3>
<p> {{ post.bodytext }}</p>
</div>
<hr>
{% endfor %}
</div>
my django project I created was called firstblog , I then have an app named blog. In the root of my project folder "firstblog" I have a folder for images and then a sub folder inside that one called heroimage.
Can anyone help me get this working?
Thanks
It is appended to your MEDIA_ROOT setting.
https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.FileField.upload_to
Set a media root for uploaded files the to retrieve the files, ill give you an example:
# settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# models
class Blog(models.Model):
main_image = models.ImageField(default='none/none.jpg', upload_to='blog'
# template
<img src="/media/{{ blog.main_image }}">
# media folder after
media/blog/imageuploaded.jpg
media/none/none.jpg # This file was already created
To upload to the static directory change
MEDIA_ROOT = STATIC_ROOT or STATICFILES_DIRS[0]
Though this is absolutely not recommended!
I'm doing an app with Django Non Rel on GAE, and i want to show the Profile Image of the user in the template but i can't here is the model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class userProfile(models.Model):
def url(self, filename):
url = "MultimediaData/Users/%s/%s"%(self.user.username, filename)
return url
user = models.OneToOneField(User)
email_public_user = models.EmailField(blank=True, null=True)
url_user = models.CharField(max_length=200, blank=True, null=True)
company_user = models.CharField(max_length=200, blank=True, null=True)
position_user = models.CharField(max_length=200, blank=True, null=True)
photo_user = models.ImageField(upload_to=url)
def __unicode__(self):
return self.user.username
For now i'm adding the photo via admin to see if i can show the image, here is the template
<div class="navbar-header nav-img">
{% if user.get_profile.photo_user %}
<img class="navbar-brand" src="{{user.get_profile.photo_user}}">
<p class="navbar-brand">{{user.get_username}}</p>
{% else %}
<img class="navbar-brand" src="/media/img/principal_html/img1.png">
<p class="navbar-brand">{{user.get_username}}</p>
{% endif %}
It shows the username, but not the image, i put the user.get_profile.photo_user in a and i got this
ahRkZXZ-c29mdHN5c3RlbWFuYWdlcnIiCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGICAgICAzKYKDA/MultimediaData/Users/[username]/img.jpg
There's no view yet because im uploading the image using the django admin and when i save the user with his photo shows the same url
How can i solve this? I need to show the image...plz help