I got a problem displaying photos from my uploads folder.
I have a form where user can enter title, description and upload a image, then insert it into database. I can display all the data I just added on my template except the image, there just a X instead of image.
ps. image is successfully downloaded to uploads folder and it filename successfully added to database. It just doesnt display on the page.
app.py
#route to content page
#app.route('/dashboard', methods = ['GET', 'POST'])
def dashboard():
error = None
form = MessageForm()
if form.validate_on_submit():
filename = secure_filename(form.photo.data.filename)
form.photo.data.save(os.path.join('uploads/', filename))
new_message = BlogPost(
form.title.data,
form.description.data,
form.photo.data.filename,
current_user.id
)
db.session.add(new_message)
db.session.commit()
flash("Your recipe was successfully posted. Thanks!")
posts = db.session.query(BlogPost).all()
return render_template('dashboard.html', posts = posts, form = form,
error = error)
else:
posts = db.session.query(BlogPost).all()
return render_template('dashboard.html', posts = posts, form = form,
error = error)
template
{% for post in posts %}
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-5 masonry-item">
<div class="box-masonry"><a href="#" title="" class="box-masonry
image with-hover-overlay">
<img src="uploads/{{ post.photo }}" alt="" class="img-responsive"
</a>
<div class="box-masonry-hover-text-header">
<h4> {{ post.title }}</h4>
<div class="box-masonry-desription">
<p>{{ post.description }}</p>
<p><strong>{{ post.author.name }}</strong></p>
</div>
</div>
</div>
</div>
{% endfor %}
From the Flask Doc :
To generate URLs for static files, use the special 'static' endpoint
name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
And in your case you should use:
{{ url_for('static', filename='uploads/' + post.photo) }}
Related
I am using Cryptocompare.com api to load news from cryptocurrencies world. In the template I am looping through it show it on the home-page. I would like to add feature that if you click send button it will send an email to you with the link for the news you just clicked. What is the best way to do it? I tried that, but I dont know how to link the clicked element with the url in views.
def home(request):
# Grab Crypto News
api_request = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN')
api = json.loads(api_request.content)
return render(request, 'crypto/crypto_home.html', {'api': api})
def SendLink(request):
if request.method == 'POST':
subject = 'Link to crypto news'
from_email = 'test#gmail.com'
message = 'Hello {}, here is your link:'.format(request.user)
to_email = [request.user.email]
send_mail(
subject,
message,
from_email,
to_email
)
return HttpResponseRedirect(reverse('crypto-home'))
Template:
{% for x in api.Data %}
<div class='col-sm'>
<div class="card">
<img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}">
<div class="card-body">
<h5 class="card-title">{{x.title}}</h5>
<p class="card-text">{{ x.body|safe }}.</p>
<div class="btn-group btn-group-sm" role='group'>
Read More
<form method="post" action="{% url 'send_link' %}">
{% csrf_token %}
<button id="{{x.id}}" target="_blank" class="btn btn-primary">Send to e-mail</button>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
I would like to add link from template 'x.url' to views to be able to add the link to the message variable. I also tried to link it via ID of the news but I am not able to pass it to the views. Any idea how I can do that? Thanks
It looks like you need to add a hidden field to your form for the URL you'd like to pass to your view:
<input type="hidden" id="URL" name="URL" value="{{x.url}}">
Once you have that variable in your view you should be able to add it to your email template.
I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ?
I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use.
Any ideas? (I am a beginner in django)
VIEWS.PY
from django.shortcuts import render
import requests
from . import models
def index(request):
return render(request, 'base.html')
def new_search(request): ********NOT IMPORTANT (I THINK)********
search = request.POST.get('search')
models.Search.objects.create(search=search)
objects = models.Object.objects.all()
results = objects.filter(name__contains=search).all()
args = { 'results': results }
return render(request, "my_app/new_search.html", args)
def individual_page(request):
link = request.GET.get('object-link')
objects = models.Object.objects.all()
return render(request, "my_app/individual_page.html")
MY TEMPLATE
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2 style="text-align: center">{{ search | title }}</h2>
<div class="row">
{% for result in results %}
<div class="col s4">
<div class="card medium">
<div class="card-image">
<a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a>
</div>
<div class="card-content">
<p>{{result.name}}</p>
</div>
<div class="card-action">
View listing: Price TEST
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
So, the thing I want to do is: when I press the anchor tag that includes the image, I get redirectioned to another page which contains only that one object's info.
I want to have an download button a html page that renders a django table.
I followed the documentation of django2 and this post How to export .csv with Django-Tables2? was helpful but could not make the trick.
I feel like I have done everything correctly (according to my beginner skills), there is no error but the download button is not there.
I was wondering if someone has any help to provide on this one
table.py
class AnormalTable(tables.Table):
class Meta:
model = stock_anormal
template_name = "django_tables2/bootstrap4.html"
export_formats = ['csv', 'xlsx']
view.py
#method_decorator(login_required, name='dispatch')
class PostDetailalerte_negat(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin):
def get(self, request):
queryset = stock_negatif.objects.all()
table = NegatTable(queryset)
RequestConfig(request).configure(table)
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format(export_format))
return render(request, 'detailstocknegat.html', {'table':table})
html snipet
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">ITEMS IN ALERTE SAFETY STOCK LEVEL</h1>
<div>
{% for format in view.export_formart %}
<i class="fas fa-download fa-sm text-white-50"></i> Generate Report
{% endfor %}
</div>
</div>
<table>
{% load django_tables2 %}
{% render_table table %}
</table>
I'm not sure if this will fix this specific problem but I ran into basically the same issue and this is how I solved it:
I moved the export_formats = ['csv', 'xlsx'] that was in table.py originally into the view for my table (view.py in this example). Then I passed export_formats directly to the html by changing the return code in views.py : return render(request, 'detailstocknegat.html', {'table':table, 'export_formats':export_formats}).
Then in the html for my table (html snipet in this example) I changed the for statement to be:
{%for format in export_formats %}>
<a href="{% export_url format %}">
download <code>.{{ format }}</code>
</a>
{% endfor %}
I hope this helps somebody out there!
I'm trying to reference uploaded memes on my Django web app (development mode).
I want "account" to reference "media/memes/images/{insert img}"
but it's referencing "/account/media/memes/images/{insert img}".
Below is account function in views.py:
def account(request):
user = request.user
if user.is_authenticated:
user_posts = Meme.objects.filter(author=request.user).order_by('-published')
else:
return _logout(request, timed_out=True)
files = [m.file for m in list(user_posts)]
#print("filenames to memes posted by user: ", files)
return render(request, "account.html", context={"filenames": files})
Below is account.html:
{% extends "layout.html" %}
{% block content %}
<div class="row">
{% for filename in filenames %}
<br>
<div class="col s12 m6 l4">
<div class="card-content">
<img src="media/{{ filename }}" width="80%" height="80%"></img>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
Below is the output:
[07/May/2019 21:26:40] "GET /account/ HTTP/1.1" 200 1563
Not Found: /account/media/memes/images/michaeljordan.jpg
[07/May/2019 21:26:40] "GET /account/media/memes/images/michaeljordan.jpg HTTP/1.1" 404 3418
Your problem is not related to django. Fix: src="media/ => src="/media/
Omitted leading slash means "starting from current url". Leading slash means "from the root".
Although this change fixes your issue, this is not the Django way. I suggest you to configure MEDIA_URL and refer these images like:
src="{{ m.file.url }}"`
in your case MEDIA_URL = '/media/'
I am trying to display the image and name in a for loop on my template.
This is what I have on my template for loop, and I thought it should work, but it doesn't
{% for op in tracked_objects %}
{% if op.is_mine %}
<div style="float:left;">
<div>
<img src="{{ op.tracked_object.image }}" alt="">
<a href='{% url track-profile op.tracked_object.id %}'>{{ op.tracked_object }}</a><br>
</div>
</div>
{% endif %}
{% endfor %}
I know that op.is_mine is true because the Name shows.
Here is my views.py:
#login_required
def profile(request):
user = request.user
tracked_objects = user.tracked_object_perms.all().order_by('is_mine',)
context = {
'tracked_objects':tracked_objects,
}
return render_to_response( 'accounts/profile.html' , RequestContext(request, context))
and finally the models.py
name = models.CharField(max_length='140')
image = models.ImageField(upload_to='img/tracked_object_images', null=True, blank=True)
Update
Now when I use the below anser of adding the .url onto the end, I get three broken image icons. Now I have checked the path and it goes to the correct image. Would this be a server issue possibly? Or something along those lines?
Try:
<img src="{{ op.tracked_object.image.url }}" alt="">
See Using django.contrib.staticfiles.