I am having trouble getting thumbnails working with sorl.thumbnails.
I am getting no errors.
What I have done:
settings.py
INSTALLED_APPS = {
...
'sorl.thumbnail',
}
THUMBNAIL_DEBUG = True
...
models.py
...
from sorl.thumbnail import ImageField
...
class Upload(models.Model):
article = models.ForeignKey(Article, related_name="uploads")
image = models.ImageField(upload_to=get_image_path, blank=True)
template
{% extends 'layouts/base.html' %}
{% block title %}Home - {{ block.super }}{% endblock %}
{% load staticfiles %}
{% load thumbnail %}
{% block content %}
<section class="main clearfix">
{% for article in articles %}
<div class="work">
<a href="{% url 'article_detail' slug=article.slug %}">
{% for upload in article.uploads.all %}
{% thumbnail article.image "200x200" as im %}
<img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"class="media" alt=""/>
{% endthumbnail %}
{% endfor %}
<div class="caption">
<div class="work_title">
<h1>{{ article.name }}</h1>
</div>
</div>
</a>
</div>
{% endfor %}
</section><!-- end main -->
{% endblock %}
views.py
...
def index(request):
articles = Article.objects.all().order_by('-featured')
return render(request, 'index.html', {
'articles': articles,
})
def article_detail(request, slug):
#grab the object
article = Article.objects.get(slug=slug)
#grab all object Images
uploads = article.uploads.all()
# pass to the template
return render(request, 'articles/article_detail.html', {
'article': article,
'uploads': uploads,
})
...
urls.py
...
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$','django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
]
...
I have been stuck on this for a while. Any help would be greatly appreciated.
Check the following:
does {{ article.image.urlĀ }} output anything?
does {{ im.url }} output anything?
is any thumnail created when you load the page? Check your media folder.
are you sure THUMBNAIL_DEBUG is True?
./manage.py shell
from django.conf import settings
print settings.THUMBNAIL_DEBUG
pip freeze => double check the doc for the version you're using
Also, you have an optional image:
image = models.ImageField(upload_to=get_image_path, blank=True)
so you probably want to check if there is an image:
{% if article.image %}
THE THUMBNAIL
{% else %}
A PLACEHOLDER?
{% endif %}
Ah, the image is on your Upload model !
Replace:
{% thumbnail article.image "200x200" as im %}
With:
{% thumbnail upload.image "200x200" as im %}
My other answer stay true though. You need to check if there is an image:
{% if upload.image %}
Related
I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration?
views.py
def add_carpet(request):
context_dict = {}
carpet_form = forms.CarpetForm()
if request.method == "POST":
carpet_form = forms.CarpetForm(request.POST)
if carpet_form.is_valid():
carpet = carpet_form.save()
return redirect(reverse(
"dashboard_add_images",
kwargs={
"model_type": "carpet",
"id": carpet.id
}
))
context_dict["carpet_form"] = carpet_form
return render(
request,
'dashboard/add_carpet.html',
context_dict
)
def add_images(request, model_type, id):
...
add_images.hml
{% extends 'layouts/dashboard_base.html' %}
{% load django_bootstrap5 %}
{% load static %}
{% block title %}Add Images{% endblock title %}
{% block content %}
<div class="row">
<div class="col justify-content-end">
<h1 class="heading half_space text-muted">
Add Images for the {model}
<span class="divider-left"></span>
</h1>
</div>
</div>
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}
{# Display a form #}
<form enctype="multipart/form-data" action="{% url 'dashboard_add_images' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% bootstrap_button button_type="submit" content="OK" %}
</form>
{% endblock content %}
From above you can see I added the enctype on the form but still no change.
urls.py
urlpatterns = [
path('add_carpet', views.add_carpet, name="dashboard_add_carpet"),
path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),]
An example redirect url after a form has been submitted is this:
http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70
Error:
Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$']
{% extends "base.html" %}
{% load static %}
{% block content %}
<h1>{{ project.title }}</h1>
<div class="row">
<div class="col-md-8">
**<img class="img-fluid" src="{{project.image}}">**
</div>
<div class="col-md-4">
<h5>About the project:</h5>
<p>{{ project.description }}</p>
<br>
<h5>Technology used:</h5>
<p>{{ project.technology_used }}</p>
</div>
</div>
{% endblock %}
I got this error:
[20/Feb/2021 21:49:31] "GET /project/1 HTTP/1.1" 200 1427
Not Found: /project/static/img/1-webgrow.jpg
and the static folder is in project directory.
This is the view function:
def details(request, pk):
project = Project.objects.get(pk=pk)
context = {
'project': project
}
return render(request, 'details.html', context)
please help
you forgot to use .url in your code
It should be like this
<img class="img-fluid" src="{{project.image.url}}">
and also, the images of models are not stored in statics folder, their in media root
**Can someone please help me solve this problem I just started learning Django.
I keep getting getting "PAGE NOT FOUND " whenever i open/click the list/entries
In my "entries" folder i have
Css.md
Django.md
Git.md
Python.md
HTML.md**
screenshot of "Page not found"
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry, name="entry"
views.py
from django import forms
class NewEntryForm(forms.Form):
title = forms.CharField(max_length=100)
content = forms.CharField(widget=forms.Textarea)
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def entry(request, entry):
entries = util.get_entry(entry)
if entries is None:
return render(request, "encyclopedia/error.html", {
"message1": "Sorry",
"message2": "your requested page was not found "
})
return render(request, "encyclopedia/index.html", {
"content": entries,
"form": NewEntryForm
})
index.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<h1>All Pages</h1>
<ul>
{% for entry in entries %}
<li></li>
{% endfor %}
</ul>
{% endblock %}
entry.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
Encyclopedia - {{title}}
{% endblock %}
{% block body %}
<div class="container">
<div class="row">
{% if not content%}
<div>Sorry, your requested page was not found </div>
{% else %}
{{ content | safe }}
<div>Edit this entry</div>
{% endif %}
</div>
</div>
{% endblock %}
edit anchor tag in entry.html. URL is given wrong, Do this
<div><a href="{% url 'entry' entry %}>Edit this entry</a></div>
instead of
<div><a href="{% url 'edit' entry %}>Edit this entry</a></div>
you forget to close "".
write this:
<div>Edit this entry</div>
simple.....
I was working a project on mine, in which I needed to provide a class to a field in form which is a input box, but don't know how to do so.
My Template:
{% extends 'diary/base.html' %}
{% block title %}Register{% endblock title %}
{% block content %}
{% load staticfiles %}
<link rel= "stylesheet" type= "text/css" href = "{% static 'users/register.css' %}">
<div id="login-box">
<div class="left-box">
<h1>Register</h1>
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{% for non_field_error in form.non_field_errors %}
<p>{{ non_field_error }}</p>
{% endfor %}
{% for field in form %}
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
{% endfor %}
<input type="submit" value="SIGN UP" name="signup-button" class="signup-btn">
</form>
</div>
<div class="right-box">
</div>
</div>
{% endblock content %}
In this specific part:
{% for field in form %}
{{ field }}
{% for error in field.errors %}
I want to provide a class to {{ field }}.
I tried this:
{{ field(class="txtb") }}
This is how I use to provide a class in Flask, but in Django this didn't worked.
Any Help Would Be Appreciated!
django-widget-tweaks
I'm using django-widget-tweaks module for set HTML attribute in templates.
installation
install module using pip install django-widget-tweaks
add to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
...
'widget_tweaks',
...
]
{% load widget_tweaks %} in templates file
usage
in templates code:
{% load widget_tweaks %}
...
{% for field in form %}
{% render_field field class="txtb" %}
...
in HTML, looks like this:
<input class="txtb" ... ...>
reference django-widget-tweaks github page for more information.
manually
Detailed description is in here
forms.py:
class YourForm(forms.ModelForm):
modelfield = forms.CharField(
...,
widget=forms.TextInput(
attrs={
'class': 'txtb'
}
}
)
class Meta:
model = ...
fields = ...
And I have a lot of information about django to simpleisbetterthancomplex.com
django-widget-tweaks also learned here
I am working on a photo app, which allows one to upload images. From there, there are choice options for each photo -- either "PUBLIC" or "PRIVATE"--. For images that are "PUBLIC", the image will be shown on the home page without need for user authorisation. However, I am finding difficulty in filtering the images based on the choices and display the relevant object on the home page.
I am new to coding and Django, would appreciate some advice here. Thanks in advance!
This is my models.py file:
class Images(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='images/')
PRIVATE ='PR'
PUBLIC = 'PU'
PUBLISH_CHOICES = [
(PRIVATE, 'Private'),
(PUBLIC, 'Public'),]
publish = models.CharField(max_length=7,
choices=PUBLISH_CHOICES,
default=PRIVATE)
def __str__(self):
return self.title
This is my views.py file
class HomePageView(ListView):
model = Images
template_name = 'index.html'
def my_view(request):
myimages = Images.objects.all()
for entry in myimages:
publish_status = entry.get_publish_display()
return publish_status
This is my index.html file:
{% for images in images_list %}
{% if publish_status == Public %}
<div class="container">
<h3>{{images.title}}</h3>
<img src="{{images.image.url}}" alt=" {{images.title}}">
</div>
{% endif %}
{% endfor %}
The generic ListView returns a list of all Images, you can the pass them to the template - as you rightfully did - and then filter by publish field could be PU for Public or PR for Private.
views.py becomes:
class HomePageView(ListView):
model = Images
template_name = 'index.html'
index.html becomes:
{% for images in images_list %}
{% if images.publish == 'PU' %}
<div class="container">
<h3>{{images.title}}</h3>
<h2>{{ images.image.url }}</h2>
<img src="{{ images.image.url }}" alt="{{images.title}}">
</div>
{% endif %}
{% endfor %}
Cheers.
You can get all images, pass them to template and then filter based on publish_status. Below is how it might look like.
views.py:
class HomePageView(ListView):
model = Images
template_name = 'index.html'
index.html:
{% for image in object_list %}
{% if image.publish_status == 'Public' %}
<div class="container">
<h3>{{images.title}}</h3>
<img src="{{images.image.url}}" alt=" {{images.title}}">
</div>
{% endif %}
{% endfor %}
{% for image in object_list %}
{% if image.publish_status == 'Public' %}
<div class="container">
<h3>{{images.title}}</h3>
<img src="{{images.image.url}}" alt=" {{images.title}}">
</div>
{% endif %}
{% endfor %}
Try this. Edit your index.html file