Django, set img src dynamically - html

Before someone marks this as duplicate I have read and tried solutions in these threads:
Use Django Template Tags in img src
django 1.5 - How to use variables inside static tag
Django: Insert image in a template whose path is dynamic
And still have not been able to get it to work.
So I'm using Django built in UpdateView to update an data base entry and I'm trying to load image to template where part of src is dynamic like this:
edit_journal_entry_form.html
{% extends 'base.html' %}
{% load staticfiles%}
<form method="post">
{% csrf_token %}
{% static "" as baseUrl %}
<img src="{{ baseUrl }}/lpr_images/{{journalEntry.license_plate_nr_img}}"></img>
<img src="{% static "" %}/lpr_images/{{journalEntry.license_plate_nr_img}}" />
<img id="edit_img" src="{% static 'lpr_images/' %}{{journalEntry.license_plate_nr_img}}" alt="Image not read!"/>
{{ form.as_p }}
<button class="btn btn-success" type="submit">Submit</button>
...
views.py
class JournalEntryUpdate(UpdateView):
model = JournalEntry
template_name = 'gate_operator/edit_journal_entry_form.html'
success_url = '/gate_operator/journal/'
fields = [
'license_plate_nr',
'license_plate_nr_img',
...
]
def form_valid(self, form):
object = form.save(commit=False)
object.user = self.request.user
object.save()
return super(JournalEntryUpdate, self).form_valid(form)
models.py
class JournalEntry(models.Model):
license_plate_nr = models.CharField(max_length=20, blank=True)
license_plate_nr_img = models.CharField(max_length=100, blank=True)
...
None of this works in console I can se that I'm getting only the static part: GET http://127.0.0.1:8000/static//lpr_images/ 404 (Not Found)
I tried to hard code the url just to make sure I'm on the right path, so this successfully shows image: http://127.0.0.1:8000/static//lpr_images/2018_04_26_08_43_25.png
So what am I missing here or doing wrong?

In the template, you should use journalentry (all lowercase), instead of journalEntry.

Related

django-filters form not showing(only the submit button does)

template
<form method="get">
{{ filter.form.as_p }}
<input type="submit" value="Press" />
</form>
{% for obj in filter.qs %}
{{ obj.WorkType }} - ${{ obj.desired_wage }}<br />
{% endfor %}
views
#login_required(login_url='login')
def ListingsPage(request):
review = Review.objects.all()
filter = Profilefilter(request.GET, queryset=Profile.objects.all())
context = {"profile":profile,"review":review,"filter":filter}
return render(request,"base/Listings.html",context)
filters.py
import django_filters
from .models import Profile
class Profilefilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='iexact')
class Meta:
model = Profile
fields = ['WorkType', 'gender']
urls.py
urlpatterns = [
path('Listings/', views.ProfileSearch, name='profile_search_bar'),
path('',views.hello,name="home"),
path('Listings/', views.ListingsPage,name="listings"),
It is supposed to be showing the filters but doesn't render anything, only the submit button shows up. I think it is something to do with passing the context, not sure tho
You need to add qs for query filter
def ListingsPage(request):
review = Review.objects.all()
filter = Profilefilter(request.GET, queryset=Profile.objects.all())
review = filter.qs
context = {"profile":profile,"review":review,"filter":filter}
return render(request,"base/Listings.html",context)

DJANGO template tags in plain text not displaying

I am making an app that displays questions. The question model has a text field and an image field. Each question has a template that is stored in my database in the text field. My problem is when I want to access images from the model, template tags are displayed as text and not rendering. My code:
# question model
class Question(models.Model):
question_text = models.TextField()
question_image = models.FileField(upload_to='static/images/questions', blank=true)
# question view
def question(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'questiontemplate.html', {'question': question})
# template
{% extends 'base.html %}
{% load static %}
{% autoscape off %}
{{ question.question_text }}
{% endautoscape %}
# in my database:
question.question_text = '<p> some html
{{ question.question_image.url }}
some html </p>'
question.question_image = 'image.png'
This works fine and renders the html perfectly except the template tag is not rendered and does not not give the image url
I want this to be the output:
Some html
static/images/questions/image.png
some html
But instead this is the output:
some html
{{ question.question_image.url }}
some html
Any suggestions to how the template tags could be render from the database text would be much appreciated.
Thanks for reading
Django doesn't know that the content in your model field is itself a model. The template can't know that. The only way to make this work is to treat that field itself as a template, and render it manually.
You could do that with a method on the model:
from django.template import Template, Context
class Question(models.Model):
...
def render_question(self):
template = Template(self.question_text)
context = Context({'question': self})
rendered = template.render(context)
return mark_safe(rendered)
Now you can call it in your template:
{{ question.render_question }}

Django ImageField not render at <img> tag HTML

# models.py
from django.db import models
from . import constants
class Photos(models.Model):
band_member = models.ForeignKey(BandMember,on_delete=models.CASCADE)
photo = models.ImageField(upload_to='media/')
photo_description = models.TextField(max_length=400)
class Photos(models.Model):
band_member = models.ForeignKey(BandMember,on_delete=models.CASCADE)
photo = models.ImageField(upload_to='media/')
photo_description = models.TextField(max_length=400)
#property
def photo_url(self):
if self.photo and hasattr(self.photo, 'url'):
return self.photo.url
# views.py
def member_photos(request,member_id):
current_member = BandMember.objects.get(pk=member_id)
photos = current_member.photos_set.all()
context = {
'all_photos': photos,
'current_member': current_member,
}
return render(request,'band_members/member_photos.html', context)
html file :
{% if all_photos %}
{% for foto in all_photos %}
<img class"" src="{{ foto.photo_url }}"
alt = {{foto.photo_url }}">
<h5>{{ foto.photo_description }}</h5>
{% endfor %}
Although , image is not displayed , alt displays the correct path of the file
What am i doing wrong ?
What i'm trying to achieve , is when user clicks on a 'SHOW PHOTOS' button at a page containing informations about a specific band member
(site/band_member/member_id here ), another page loads (site/band_member/member_id/photos) , displaying all the photos of the current member.
NEW TO DJANGO !!!
Thank you !
sorry for my 'bad english' language :)
The html inside the loop is not correct. Try fixing that like this.
<img src="{{ foto.photo_url }}" alt ="{{foto.photo_url }}">
<h5>{{ foto.photo_description }}</h5>

Working with links in Django

I am working in a small blog application using Django. Sorry if the question is obvious, but I am a newbie. Actually it is my third since I started an online course. I have the following Queryset:
def all(request):
allTiles = Post.objects.values('title')
allPosts = Post.objects.all()[:3]
context = {'Posts': allPosts,"Titles":allTiles}
template = "home.html"
return render(request, template, context)
and the follwing html code:
<ol class="list-unstyled">
{% for singleTile in Titles %}
<li>{{singleTile.title}}</li>
{% endfor %}
</ol>
As you can see every title creates an link. Lets assume a person decides to read one of the posts. How can I use the title name and send a request back to the database to get the content of the post.
It is better to use the id or slug field for such task.
But if you surely want to use the title as the GET parameter then apply the urlencode filter to the field's value:
<a href="{% url 'post_detail' %}?title={{ singleTile.title|urlencode }}">
{{ singleTile.title }}
</a>
And the view will be something like this:
def post_detail(request):
post = get_object_or_404(Post, title=request.GET.get('title'))
return render(request, 'post_detail.html', {'post': post})
UPDATE: If you decide to go with the id/slug option then you can use the generic DetailView:
<a href="{% url 'post_detail' singleTile.id %}">
{{ singleTile.title }}
</a
urls.py:
from django.views.generic.detail import DetailView
from app.models import Post
url(r'^post/(?P<pk>\d+)/$', DetailView.as_view(model=Post),
name='post_detail')
You have to configure url first like
{% url 'app.views.post_id' singleTile.id %}</li>
In your urls
url(r'^post/(?P<post_id>\d+)/$', views.by_id, name='post_id'),
And in your views
def post_id(request, post_id):
allTiles = Post.objects.get(id=post_id)
return render(request, template, context)

Flask-SQLAlchemy queries

I am having issues with a seemingly simple sqlalchemy query using Flask.
I have a table called Links and within that table there are columns called 'id', 'author_id', 'link', and 'group'. My models.py looks like this:
class Links(db.Model):
__tablename__='links'
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
link = db.Column(db.String, unique=False, nullable=True)
group = db.Column(db.String, unique=False, nullable=False)
def __init__(self, author_id=None, link=None, group=None):
self.author_id = author_id
self.link = link
self.group = group
def __repr__(self):
return'<Link %r>' %(self.link)
I would like to return the values of all groups associated with the user that is logged into the application. Here is my views.py file:
#app.route('/members/', methods=['GET','POST'])
#login_required
def members():
error=None
form = PostLink(request.form, csrf_enabled = False)
uid = session['user_id']
link = "NULL"
groups = Links.query.filter_by(author_id=uid).all()
if request.method=='POST':
if form.validate_on_submit():
new_group = Links(
uid,
form.group.data,
link,
)
try:
db.session.add(new_group)
db.session.commit()
flash("You have created a group!")
except IntegrityError:
error = 'That group did not work, maybe it already exists?'
else:
flash_errors(form)
return render_template('members.html', form=form, error=error, link = link, groups=groups)
And my 'members.html':
{% extends "base.html" %}
{% block content %}
<p>Add New Group: {{ form.group }}</p>
<input id="link" type="hidden" name="link" value= {{ link }}/>
<p><input type="submit" value="Request"></p>
</form>
<br/>
{% for group in groups %}
<li><p>
{{ group }}
</p></li>
{% endfor %}
{% endblock %}
Currently this is just returning a list of links and groups in an odd format:
<Link u'link2'>
<Link u'linky'>
<Link u'linkymaybe'>
<Link u'madeit'>
<Link u'BLAH'>
So the core of my question is how do I build a query using SQLAlchemy to display all groups associated with the logged in user (uid = session['user_id']) I am pretty new to Flask and this problem is becoming an issue as I have tried a number of filter_by and filter statements with no luck at all.
Thank you in advance!
It is displaying correctly the object "Link" returned by the query.
You need to format it in the template.
Thisi is link {{ group.link }} from author #{{ group.author_id }} in group named {{ group.group }}
Maybe you've chosen a bad name "group" when cycling on results in the template. It should be called link.
In the template, you can show the group name using {{ link.group }} instead of {{ link }}. The query is returning the whole object.