I'm using this package https://github.com/tomwalker/django_quiz to make a web quiz app. I need to add images to the multiplechoice answers.
So, I added to the Answers model:
image = models.ImageField(upload_to='uploads/%Y/%m/%d',
blank=True,
null=True,
verbose_name=_("Image"))
Images are uploading and saving into the DB.
The part that shows choosable answers are shown in template like this:
{% for answer in form.answers %}
<li class="list-group-item">
{{ answer }}
</li>
{% endfor %}
I changed it to:
{% for answer in form.answers %}
<li class="list-group-item">
{{ answer }}
<img src="{{ answer.image.url }}" alt="" />
</li>
{% endfor %}
But it's doesn't work. It renders <img src(unknown)>
This is forms.py:
class QuestionForm(forms.Form):
def __init__(self, question, *args, **kwargs):
super(QuestionForm, self).__init__(*args, **kwargs)
choice_list = [x for x in question.get_answers_list()]
self.fields["answers"] = forms.ChoiceField(choices=choice_list,
widget=RadioSelect)
And this is model:
def get_answers_list(self):
return [(answer.id, answer.content) for answer in
self.order_answers(Answer.objects.filter(question=self))]
I know this is old but I recently came across this problem, in case anyone out there is still stuck on it, here is how I solved it:
Create a ImageField in the Answer model
image = models.ImageField(upload_to='images/',
blank=True,
null=True,
verbose_name=_("Image"))
Add a model method on MCQuestion
from django.utils.safestring import mark_safe
...
def get_answers_images(self):
return [(answer.id, mark_safe(f"<img src='{answer.image.url}'/>")) for answer in
self.order_answers(Answer.objects.filter(question=self))]
In forms.py
image_choice_list = [x for x in question.get_answers_images()]
self.fields["answers"] = forms.ChoiceField(choices=image_choice_list,
widget=RadioSelect)
PS: You might also want to change your QuizTake in views.py in other to not conflict with other types of questions, in my case I separated the forms for MCQuestion and TFQuestion
# New
elif self.question.__class__ is TF_Question:
form_class = TF_QuestionForm
I hope this saves someone else from wasting hours on something relatively simple. While injecting the img tag directly might not be the "cleanest" approach I think it works well enough and doesn't require you to mess around much with the existing logic structure of the quiz app.
to display image :-
add {% load static %} in template
sample snippet:-
{% block content %}
{% load static %}
Product List
{% if product %}
{% for prd in product %}
<div class="gallery">
<a target="_blank" href="{% static prd.image1 %}">
<img src="{% static prd.image1 %} " alt="{{ prd.name }}" width="400" height="400">
</a>
<div class="desc"> {{ prd.name }}</div>
</div>
{% endfor %}
{% else %}
<p>There are no products entered by you .</p>
{% endif %}
{% endblock %}
in url.py
from django.conf.urls import url
from django.contrib import admin
**from django.conf import settings**
**from django.conf.urls.static import static**
from . import views
from .views import Productlistview,Productdetailview
app_name= 'product'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^add/$', views.addproduct, name='addproduct'),
url(r'^addsuccess/$', views.addsuccess, name='addsuccess'),
url(r'^productview/$', Productlistview.as_view(), name='viewproduct'),
url(r'^productview/(?P<productid>[0-9a-f-]+)/view/$',Productdetailview.as_view(), name='productdetailview'),
] **+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**
in settings.py -- project setings
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/dev/projects/pro_mysql_practice/product/',
'dev/projects/pro_mysql_practice/index/',
]
Related
I'm trying to get my django model to be shown in the footer of my base.html but I can't get it to show up. I've looked at a few videos and I can't figure out where I'm going wrong. I know that the model works as I've made 4 entries in my database and I can view them on the admin page. The code also doesn't show any errors so I have nothing to go off of there. Here it is:
Models.py
class SocialMediaPlatform(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
font_awesome_class = models.CharField(max_length=50, blank=True, null=True)
base_url = models.CharField(max_length=50, blank=True, null=True,
default='https://instagram.com/ or https://tiktok.com/#')
def __str__(self):
return self.base_url
Views.py
def social_media_base_view(request):
context = {}
smbase = SocialMediaPlatform.objects.all()
context['smbase'] = smbase
return render(request, 'base.html', context)
Urls.py
urlpatterns = [
path('', views.social_media_base_view),
]
Admin.py
#admin.register(SocialMediaPlatform)
class SocialPlatformAdmin(admin.ModelAdmin):
list_display = ('name', 'font_awesome_class', 'base_url')
base.html
{% for smlink in smbase %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
Look what you are passing as context:
def social_media_base_view(request):
...
smbase = SocialMediaPlatform.objects.all()
context['smbase'] = smbase
return ...
It's QuerySet of SocialMediaPlatform objects. It means, that you can render them one by one with for loop:
{% for smlink in smbase %}
{{ smlink.name }}
{% endfor %}
You don't need to call SocialMediaPlatform model additionaly.
in your view you use:
return render(request, 'index.html', context)
i can not see, if you are defined index.html
Somethere in index you should have
{% extends base.htm %}
The second, i am agree with #Shabble:
{% for smlink in smbase %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
The last:
Try to use Django-GCBV TemplateView. Or ListView, in your case it is better:
somethere in views.py
Class MyListView(ListView):
model = SocialMediaPlatform
template_name = index.html
somethere in urls.py
urlpatterns = [
path('', MyListView.as_view()),
]
somethere in index.html
{% for smlink in object_list %}
<a href="{{ smlink.name }}">
<i class="{{ smlink.font_awesome_class }}">
</a>
{% endfor %}
I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.
My html page
<a href="{% url "post-detail-page" slug=post.slug %}">
<h2>{{post.tractor_company}} || {{post.tractor_model}}</h2>
<pre><h5>{{post.implimentaion}}</h5>
{{post.farmer}}
Uplode Date : {{post.date}}</pre>
</a>
</div>
URLs.py
from . import views
urlpatterns = [
path("",views.starting_page,name = "starting-page"),
path("posts",views.posts,name = "post-page"),
path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]
View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
def add_post(request):
pass
def post_detail(request,slug):
indentified_post = get_object_or_404(Post,slug=slug)
return render(request,"blog/post-detail.html",{'post':indentified_post})
i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<br>
<h1 style="text-align:center;">All Tractors</h1>
<ul>
{% for post in posts %}
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}```
Try this:
{% url 'post-detail-page' post.slug as post_detail_url %}
<a href="{{ post_detail_url }}">
Let me know if it worked.
I am new to django and I am trying to build web site for my friend how makes handmade lamps.
My problem is that I have 3 different models that contains different types of lamps, and I want to get access to certain picture in any of this 3 models and display a picture and description on the other page,but it shows only some pictures from first model and for others throws an error.
this is my html and views.py codes.
{% for q in project1.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' q.pk%}">
<img src="{{q.image.url }}">
</a>
</div>
{%endfor%}
{% for e in project2.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' e.pk %}">
<img src="{{e.image.url}}">
</a>
</div>
{%endfor%}
{% for s in project3.reverse|slice:":2"%}
<div class="image-selected__lamps">
<a href="{% url 'project_detail' s.pk %}">
<img src="{{s.image.url}}">
</a>
</div>
{%endfor%}
enter image description here
def project_detail(request, pk):
project = (LampType1.objects.get(pk=pk), LampType2.objects.get(pk=pk), LampType3.objects.get(pk=pk))
context = {
'project': project,
}
return render(request, 'project_detail.html', context)
Edward this might be happening because you are passing the same id/pk to all the models and you got a picture from the first model and not from the other because an object with that id/pk does not exit in the other models.
To check, register your models in the admin and check weather an object with that particular id exit or not.
check if these steps have been done
model
class LampType1(models.Model):
title = models.CharField(max_length=40)
description = models.TextField()
image = models.ImageField(upload_to='media')
#not
#image = ImageField(upload_to='media')
settings.py
MEDIA_URL = 'media/'
MEDIA_ROOT = Path.joinpath(BASE_DIR,'media')
urls.py
from django.conf.urls.static import static
from django.conf import setting
urlpatterns = [.....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.contrib import admin
html
{% for p in project %}
<img src="{{ p.image.url }}">
{% endfor %}
Hello I am a beginner with Django and Python. I am currently in my project using a for loop in the template but it does not show anything. Could someone help me and explain me what I am doing wrong?
models.py
class ImageCategory(models.Model):
name = models.CharField(blank=False, max_length=120)
created_at = models.DateTimeField(default=datetime.now(), blank=True)
class Meta:
verbose_name_plural = "image categories"
def __str__(self):
return self.name
views.py
from .models import ImageCategory
def HomeView(request):
template = loader.get_template('editor.html')
return HttpResponse(template.render())
def LibraryOverviewView(request):
return render(request, 'library_overview.html', {'image_categories': ImageCategory.objects.all()})
So I put the category information in the libraryOverView, but the editor.html is using HomeView. library_overview.html is included in another html called editor.html
editor.html
section class="toolbox document-tools">
<ul>
<li class="tb-title">Document</li>
<!-- uncomment to see all available styles -->
<!--
<li class="tb-btn tb-btn-big tb-btn-disabled">Preview</li>
-->
<li class="tb-btn tb-btn-big" id="btn-export">Export</li>
<li class="tb-btn tb-btn-big tb-btn-action">Save</li>
</ul>
</section>
</span>
{% include 'library_overview.html' %}
{% include 'library_categories/colorful_images.html' %}
{% include 'library_categories/colorful_images_categories/blue_images.html' %}
</span>
library_overview.html
{% for category in image_categories %}
<a class="tb-btn tb-btn-label tb-btn-radio no-bg slide-forward">-> {{ category.name }}</a>
{% empty %}
<p> There are no Categories yet </p>
{% endfor %}
urls.py
urlpatterns = [url(r'^library_overview/', views.LibraryOverviewView,
name='LibraryOverviewView'),
The editor.html is using the HomeView, and not LibraryOverviewView. But the html for libraryOverviewView was included inside editor.html, thus still using the HomeView. Moving the information from LibraryOverView to HomeView worked.
In my project i had set my media folder like this:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then in my models.py i create a class like this one:
class PD_Pictures(models.Model):
pic_IDmod = models.ForeignKey(PD_Models, related_name='modello')
pic_image = models.ImageField()
pic_descr = models.CharField(max_length=50)
def __str__(self):
return self.pic_descr
at this point in my function in views.py I extract all values in db related to PD_Picture:
prod_img = PD_Pictures.objects.all()
.....
return render(
request,
'base_catalog.html',
{
'bike_mod': bike_models,
'prod_img': prod_img,
'cat_list': cat_list,
'menu_list': menu_list['menu'],
'pcontent': menu_list['cont'],
'form': c_form
},
context
)
and in my template, i would ti display related images:
{% for pic in prod_img %}
<div class="4u">
<span class="image fit"
<img src="{{ pic.pic_image }}" alt="" />
</span>
</div>
{% endfor %}
Well, at this point when I insert a new image in db, in table the path is newimage.jpg, physically on my server the image was stored in /media/newimage.jpg, how can I extract the value from the table and concatenate to the media path in my template? (<server>/media/newimage.jpg)
I have tried to use upload_to='/models/' in my ImageField but the only effect is to save image into another model folder into main model.
just try like this
{% for pic in prod_img %}
<img src="{{ pic.pic_image.url }}" alt="" />
{% endfor %}
From django official doc:
FieldFile.url
A read-only property to access the file’s relative URL by calling the url() method of the underlying Storage class.
if you try to print in your template {{ pic.pic_image }} you'll receive the db field value, while with {{ pic.pic_image.url }} the url() method from django.core.files.storage.Storage will call, and your base settings
would seem to be correct
Can you make this into your template and see what path is given?
{% for pic in prod_img %}
<p>{{ pic.pic_image }</p>
{% endfor %}