Django/python images not displayed - python

I'm trying to show an image in Django, the problem is it won't show up when I add the HTML template, I have tried all combinations (ex: {{ cars.image_main.url }}, {{ car.image_main.url }}).
If I delete all the HTML form Template and write {{ cars.image_main.url }} the image will show up. but When I put the HTML template back and insert the {{ cars.image_main.url }} into the code, the image does show up.
models.py:
class Car(models.Model):
dealer = models.ForeignKey(Dealer, on_delete=models.DO_NOTHING)
brand = models.CharField(max_length=100)
CATEGORY = (
('New', 'New'),
('Used', 'Used')
)
category = models.CharField(max_length=50, choices=CATEGORY)
image_main = models.ImageField(upload_to='images')
image1 = models.ImageField(upload_to='images', blank=True)
image2 = models.ImageField(upload_to='images', blank=True)
image3 = models.ImageField(upload_to='images', blank=True)
engine = models.CharField(max_length=100, blank=True)
stock_number = models.IntegerField(blank=True, null=True)
mpg = models.CharField(max_length=100, blank=True)
exterior_color = models.CharField(max_length=100, blank=True)
interior_color = models.CharField(max_length=100, blank=True)
drivetrain = models.CharField(max_length=100, blank=True)
mileage = models.IntegerField(blank=True, null=True)
sold = models.BooleanField(default=False, blank=False)
transmission = models.CharField(max_length=50, blank=True)
YEAR_CHOICES = [(r, r) for r in range(2005, datetime.date.today().year+1)]
year = models.IntegerField(
('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
power = models.IntegerField()
fuel = models.CharField(max_length=50, blank=True)
price = models.IntegerField()
description = models.TextField()
date = models.DateField()
def __str__(self):
return self.brand
def get_absolute_url(self):
return reverse('car_detail', kwargs={
'car_id': self.id
})
views.py:
def car_detail(request, car_id):
cars = get_object_or_404(Car, id=car_id)
context = {
'cars': cars
}
return render(request, 'car_detail.html', context)
car_detail.html:
<li data-thumb="images/thumbnail1.jpg"> <img src="images/thumbnail1.jpg" alt="" /> </li>

Try this:
car_detail.html:
<li data-thumb="images/thumbnail1.jpg"> <img src="{{ cars.image_main.url }}" alt="" /> </li>

Related

How to render each item of a dictionary in django

I am working on a django project whereby users upload resumes and they are parsed before the results are save in user profile. I have achieved the parsing part and saved the data bu the problem is rendering the data. An example is in the skills field whereby the data is stored as a dictionary and therefore I cannot display them one at a time.
Here is my models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='default.jpg', upload_to='profile_images')
bio = models.TextField()
resume = models.FileField('Upload Resumes', upload_to='resumes/', null=True, blank=True,default='resume.docx')
name = models.CharField('Name', max_length=255, null=True, blank=True)
email = models.CharField('Email', max_length=255, null=True, blank=True)
mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True)
education = models.CharField('Education', max_length=255, null=True, blank=True)
skills = models.CharField('Skills', max_length=1000, null=True, blank=True)
company_name = models.CharField('Company Name', max_length=1000, null=True, blank=True)
college_name = models.CharField('College Name', max_length=1000, null=True, blank=True)
designation = models.CharField('Designation', max_length=1000, null=True, blank=True)
experience = models.CharField('Experience', max_length=1000, null=True, blank=True)
total_experience = models.CharField('Total Experience (in Years)', max_length=1000, null=True, blank=True)
whatsapp = models.URLField(null=True, blank=True)
facebook = models.URLField(null=True, blank=True)
twitter = models.URLField(null=True, blank=True)
linkedin = models.URLField(null=True, blank=True)
languages = models.CharField(max_length=1000, null=True, blank=True)
profession = models.CharField(max_length=100, null=True, blank=True)
nationality = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.user.username
# resizing images
def save(self, *args, **kwargs):
super().save()
img = Image.open(self.avatar.path)
if img.height > 100 or img.width > 100:
new_img = (100, 100)
img.thumbnail(new_img)
img.save(self.avatar.path)
And here is my views.py:
#login_required
def profile(request):
if request.method == 'POST':
profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
files = request.FILES.getlist('resume')
resumes_data = []
if profile_form.is_valid():
for file in files:
try:
# saving the file
resume = profile_form.cleaned_data['resume']
parser = ResumeParser(file.temporary_file_path())
data = parser.get_extracted_data()
resumes_data.append(data)
profile_form.instance.name = data.get('name')
profile_form.instance.email = data.get('email')
profile_form.instance.mobile_number = data.get('mobile_number')
if data.get('degree') is not None:
profile_form.instance.education = ', '.join(data.get('degree'))
else:
profile_form.instance.education = None
profile_form.instance.company_names = data.get('company_names')
profile_form.instance.college_name = data.get('college_name')
profile_form.instance.designation = data.get('designation')
profile_form.instance.total_experience = data.get('total_experience')
if data.get('skills') is not None:
profile_form.instance.skills = data.get('skills')
else:
profile_form.instance.skills = None
if data.get('experience') is not None:
profile_form.instance.experience = ','.join(data.get('experience'))
else:
profile_form.instance.experience = None
profile_form.save()
return redirect('users-profile')
except IntegrityError:
messages.warning(request, 'Duplicate resume found')
return redirect('users-profile')
profile_form.save()
messages.success(request, 'Your profile is updated successfully')
return redirect('userprofile')
else:
profile_form = UpdateProfileForm(instance=request.user.profile)
return render(request, 'user/resumeprofile.html', {'profile_form': profile_form})
#login_required
def myprofile(request, user_id):
profile = Profile.objects.get(id=user_id)
context = {'profile':profile}
return render(request, 'user/profile.html', context)
Here is my template for the profile:
<div class="mt-4">
<h5 class="fs-18 fw-bold">Skills</h5>
<span class="badge fs-13 bg-soft-blue "><p>{{user.profile.skills}}</p></span>
</div>
In the current setup, the results I am getting are as shown in the image:
A screenshot of the results being renedered
As I can see from your image, you are saving all your skills in a list. So you can try doing:
{% for skill in user.profile.skills %}
{{skill}}
{% endfor %}
If you want to print it as a list you can try it out this way:
<ul>
{% for skill in user.profile.skills %}
<li>{{skill}}</li>
{% endfor %}
</ul>

Selecting one row from Foreign Key in Django

I have the following models in Django:
class Kingdom(models.Model) :
class Meta:
ordering = ('kingdom_name', )
kingdom_name = models.CharField(max_length=128, null=True, blank=True)
def __str__(self) :
return self.kingdom_name
class Phylum_Clade(models.Model) :
class Meta:
ordering = ('phylum_name', )
phylum_name = models.CharField(max_length=128, null=True, blank=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.phylum_name
class Classe_Clade(models.Model) :
class Meta:
ordering = ('classe_name', )
classe_name = models.CharField(max_length=128, blank=True, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.classe_name
class Ordre(models.Model) :
class Meta:
ordering = ('ordre_name', )
ordre_name = models.CharField(max_length=128, blank=True, null=True)
classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.ordre_name
class Famille(models.Model) :
class Meta:
ordering = ('famille_name', )
famille_name = models.CharField(max_length=128, blank=True, null=True)
ordre = models.ForeignKey(Ordre, on_delete=models.CASCADE, null=True)
classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True)
def __str__(self) :
return self.famille_name
class Binomiale(models.Model) :
class Meta:
ordering = ('binomiale', )
nom = models.CharField(max_length=128, blank=True)
name = models.CharField(max_length=128, blank=True)
binomiale = models.CharField(max_length=128, blank=True)
famille = models.ForeignKey(Famille, related_name='famille_names', on_delete=models.CASCADE, null=True)
ordre = models.ForeignKey(Ordre, related_name='ordre_names', on_delete=models.CASCADE, null=True)
classe_clade = models.ForeignKey(Classe_Clade, related_name='classe_names', on_delete=models.CASCADE, null=True)
phylum_clade = models.ForeignKey(Phylum_Clade, related_name='phylum_names', on_delete=models.CASCADE, null=True)
kingdom = models.ForeignKey(Kingdom, related_name='kingdom_names', on_delete=models.CASCADE, null=True)
image = models.ImageField(blank=False, default='no_picture.png')
img_thumbnail = models.ImageField(blank=False, default='no_picture.png')
observations = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='Observation', related_name='observations')
def __str__(self) :
return self.binomiale
In Views.py I have the following code:
class Famille1(OwnerListView):
model = Binomiale
template_name = 'database/famille1.html'
template_name2 = 'database/especes.html'
def get(self, request) :
strval = request.GET.get("search", False)
if strval :
query = Q(name__icontains=strval) | Q(nom__icontains=strval)
query.add(Q(name__icontains=strval) | Q(nom__icontains=strval), Q.OR)
data_list = Binomiale.objects.filter(query).select_related().distinct().order_by('nom')[:12]
ctx = {'data_list' : data_list, 'search': strval}
return render(request, self.template_name2, ctx)
else:
if request.user.is_authenticated:
famille_list1 = Binomiale.objects.select_related("famille").distinct().order_by("famille__famille_name")[:12]
ctx = {'famille_list1' : famille_list1, 'search': strval}
return render(request, self.template_name, ctx)
In my html file I use the following code:
{% if famille_list1 %}
<div class="row row-cols-12 g-3">
{% for data in famille_list1 %}
<div class="col-sm-6 col-lg-2">
<a class="linkStyles3" href="{% url 'database:data_detail' data.id %}">{{ data.famille }}</a><br/>
<h6 style="color:black">{{ data.nom }}</h6>
<img class="img-thumbnail" src="{% get_media_prefix %}{{data.img_thumbnail}}" style="width:50%">
</div>
{% endfor %}
</div>
{% endif %}
</p>
The output of this is similar to the following sqlite3 command, and output (partial):
sqlite> select famille_name, nom, name, img_thumbnail from database_binomiale inner join database_famille on database_famille.id = database_binomiale.famille_id order by famille_id;
Apidae|Bourdon terreste|Bumble bee|BumbleBee_thumb.jpg
Apidae|Abeille à miel|Honey bee|HoneyBee_thumb.jpg
Apidae|Abeille à longue corne|Long Horned Bee|LongHornedBee_thumb.jpg
Apidae|Bourdon fébrile|Common Eastern Bumble Bee|CommonEasternBumbleBee_thumb.jpg
Ardeidae|Héron cendré|Grey heron|Heron_thumb.jpg
Simuliidae|Mouche noire|Black fly|BlackFly_thumb.jpg
Muscidae|Mouche domestique|House fly|HouseFly_thumb.jpg
Culicidae|Moustique|Mosquito|Mosquito_thumb.jpg
Culicidae|Moustiques éléphants|Elephant mosquito|ElephantMosquito_thumb.jpg
Corvidae|Grand Corbeau|Common Raven|Raven_thumb2.jpg
Corvidae|Geai bleu|Blue jay|BlueJay_thumb.jpg
Cardinalidae|Cardinal à poitrine rose|Rose-Breasted Grosbeak|Grosbeak_thumb.jpg
Cardinalidae|Cardinal rouge|Northern Cardinal|Cardinal_thumb2.jpg
Mustelidae|Loutre de rivière|North American River Otter|Otter_thumb2.jpg
Mustelidae|Hermine|Stoat|Stoat_thumb.jpg
My problem is that I do not want repeats of each class "Apidae","Cardinalidae","Mustelidae" etc. I want just a single example, with its image to be displayed. I have banged my head against a wall on this for longer than I care to admit.
Can someone help me?
Thankyou!
I think that you should query on the Famille model and thus check the nom, name, etc. of the related Binomiale model objects with:
data_list = Binomiale.objects.filter(
Q(famille_names__name__icontains=strval) | Q(famille_names__nom__icontains=strval)
).distinct()
The famille_names__ lookup is due to the value for the related_name=.. parameter [Django-doc], which does not make much sense.
Note: The related_name=… parameter [Django-doc]
is the name of the relation in reverse, so from the Famille model to the Binomiale
model in this case. Therefore it (often) makes not much sense to name it the
same as the forward relation. You thus might want to consider renaming the famille_names relation to binomales.

How to render data from multiple models django

I want to render data to my webpage from my django app however only two of the required slots are being rendered
my models are:
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=7, decimal_places=2)
digital = models.BooleanField(default=False,null=True, blank=True)
image = models.ImageField(null=True , blank=True)
description = models.TextField(max_length=5000, null=True)
points = models.DecimalField(max_digits=5,decimal_places=0, null=True)
and my views are
def admin_dashboard (request):
order_list = Order.objects.all()
context = {'order':order_list}
template = "admin_dashboard.html"
return render(request, 'store/admin_dashboard.html', context)
my HTML is:
{% extends 'store/admin_main.html' %}
{% load static %}
{% block content %}
{% for order in order %}
<h6>{{ order.transaction_id }}</h6>
<p>{{ order.customer }}</p>
<p>{{ order.shippingaddress }}</p>
<p>{{ order.orderitem }}</p>
{% endfor%}
{% endblock content %}
1598061443.212917
userNew
which is just the transaction id and user.
how can I have all the rest of fields filled

How to load a parameter from an object in an object?

class Product(models.Model):
subcategory = models.ManyToManyField(Subcategory, related_name="Category")
name = models.CharField(max_length=32, unique=True)
title = models.CharField(max_length=3000)
ean = models.PositiveIntegerField(blank=True, null=True, unique=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True)
origin_name = models.CharField(max_length=32, blank=True, null=True)
quantity = models.PositiveIntegerField(blank=True, null=True)
highlights = models.TextField(max_length=3000, blank=True, null=True)
description = models.TextField(max_length=3000, blank=True, null=True)
delivery = models.TextField(max_length=3000, blank=True, null=True)
selling_price = models.DecimalField(max_digits=9, decimal_places=2)
slug = models.SlugField(unique=True)
class Infobox(models.Model):
name = models.CharField(max_length=32)
measurment = models.CharField(max_length=32)
resolution = models.CharField(max_length=32)
product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
I would like to display on my detail page all infobox objects that are linked to the device, do any of you know how to do this?
THANKSSSS <3
urls.py
Add below to your urlpatterns:
path('view_infoboxes/<int:product_id>', views.view_infoboxes, name='view_infoboxes'),
views.py
def view_infoboxes(request, product_id):
template = loader.get_template('page.html')
context = {"infoboxes": Infobox.objects.filter(product=product_id)}
return HttpResponse(template.render(context, request))
page.html
...
<div class="row">
{% for infobox in infoboxes %}
<p>{{ infobox.name }}</p>
{% endfor %}
</div>
...

Display only creator's files - Django/Python

I would like to display only the pictures uploaded by the creator (user) on their individual profiles.
How would I alter my code to display that?
Thank you!
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
def get_image_url(self):
return "%s/%s" %(settings.MEDIA_URL, self.image)
def get_absolute_url(self):
return "%s/%s" %(self.creator, self.slug)
views.py:
#login_required
def account_home(request, username):
try:
u = MyUser.objects.get(username=username)
except:
u = None
photo_set = Photo.objects.all()
context = {
"photo_set": photo_set,
"notifications": notifications,
"transactions": transactions
}
return render(request, "accounts/account_home.html", context)
.html:
{% for photo in photo_set %}
<img src="{{ photo.get_image_url }}" class='img-responsive'>
<hr/>
{% endfor %}
You have a ForeignKey to user, so you can just filter the photos by that:
photo_set = Photo.objects.filter(creator=u)
or even better use the reverse relationship:
photo_set = u.photo_set.all()
Also, never ever ever ever use a blank except statement in your code. The only exception you are expecting the get to raise is MyUser.DoesNotExist, so you should catch that only.

Categories

Resources