adding multiple image in django model - python

I am trying to add multiple images to a django model, it works in admin but i am completely blank on how to show it on my template. here is what i tried, it doesn't give any error but the image doesn't show.
models.py
class Export_Trade_Data(models.Model):
country = models.ForeignKey(
BannerandInformation, on_delete=models.CASCADE, null=True)
# country_name = models.CharField('Country Name', max_length=100, default='')
trade_text = models.TextField('Text for Trade Data', null=True)
# date added
date_added = models.DateTimeField('Date Updated', auto_now=True)
def __str__(self):
return "Export Trade Data"
class ExportImage(models.Model):
country = models.ForeignKey(
BannerandInformation, on_delete=models.CASCADE, null=True)
export_trade_data = models.ForeignKey(Export_Trade_Data, on_delete=models.CASCADE)
export_sample_image = models.ImageField(
'Export Sample Image', upload_to='country', null=True)
def __str__(self):
return "Export Trade Data"
views.py
def country(request, country):
exch_val = ''
banners = BannerandInformation.objects.filter(country=country)
for b in banners:
country_name = b
exch_r = b.exch_rate
exch_cur = exch_r.split("/")[0]
######Export_Trade_Data Model#######
etrds = Export_Trade_Data.objects.filter(country_id=ct_id)
######ExportImage Model#######
expics = ExportImage.objects.filter(country_id=ct_id)
for s in expics:
etd_pic = s.export_sample_image
content = {
"etrds": etrds,
"etd_pic": etd_pic,
}
return render(request, 'country/country-page.html', content)
country-page.html
<tbody>
{% for expics in etrds %}
<tr>
<img src="/country/{{expics.export_sample_image}}" height="604px" width="527px" alt="">
</tr>
{% endfor %}
</tbody>

As long as you have relevant ExportImage queryset in the context, you should be able to render it this way:
{% for ei in export_images %}
<img src="{{ei.export_sample_image.url}}">
{% endfor %}
However, seeing your view code it's unclear what you're trying to do there. I suggest you rewrite it. The part that should get your images would look like this:
def country(request, country_id):
export_images = ExportImage.objects.filter(country_id=country_id)
return render(request,
'country/country-page.html',
{'export_images': export_images})

Related

How can I show:{{ if citizen.nizo.name == category.name }}?

I can't use i .nizo.name if citizen.nizo.name == category.name <a> should work.
my one_category.html
{% for i in citizen %}
{% if i.nizo == category.name %}
<p>if</p>
<h3> {{ i.name }} - haqida malumuot</h3> <br>
{% else %}
<p>else</p>
{% endif %}
{% endfor %}
my models.py
class Citizen (models.Model) :
name = models.CharField(max_length=255, verbose_name= "F.I.SH",blank=True,null=True) #widget=models.TextInput(attrs={'class':'form-input'})
tugilgan_sanasi = models.DateField(max_length=255, verbose_name= "Tug'ilgan sanasi",blank=True,null=True)
slug = models.SlugField(max_length=255, unique=True,verbose_name= "Slug")
yashash_manzili = models.CharField(max_length=240, verbose_name= "Yashah manzili",blank=True,null=True)
content = models.TextField(verbose_name ="Текст статьи",blank=True)
photo = models.ImageField(upload_to="photos/%Y/%m/%d/", verbose_name="Izoh",blank=True,null=True)
is_published = models.BooleanField(verbose_name= "Organilgan/Organilmagan")
time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания",blank=True,null=True)
time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения",blank=True,null=True)
nizo_shaxs =models.CharField(max_length=240, verbose_name="Nizoloshyatgan Shaxs F.I.SH",blank=True,null=True)
nizo = models.ForeignKey('Category',on_delete=models.PROTECT, null=True,blank=True, verbose_name ="Nizo не выбрана")
mah = models.ForeignKey('Mahalla',on_delete=models.PROTECT,null=True,blank=True, verbose_name= "Mahalla не выбрана")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('iib:citizen', kwargs={'citizen_slug': self.slug})
class Category(models.Model):
name = models.CharField(max_length=100, db_index=True, verbose_name="Nizo")
slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('iib:category', kwargs={'nizo_slug': self.pk})
class Meta:
verbose_name = 'Nizo'
verbose_name_plural = 'Nizo'
my views.py
def show_one_category(request,nizo_slug:str):
citizen = Citizen.objects.all()
category = get_object_or_404(Category, slug=nizo_slug)
context = {
'category':category,
'citizen':citizen,
}
return render(request, 'main/one_category.html', context)
Create a Universal Windows Project and check that you can run a project correctly
Update Windows to version 1903
load visual studio and run a Universal Windows Project. Check that it works, by running the project.
Create a new Unity project. Navigate to your project and select build to create a .sln file. Note: not Build and Release.
Make sure AppX includes a copy of the files from the subdirectory inside your project folder.
Copy 3 dll's and paste them into your AppX directory where the exe for you project is located. They are: vccorlib140_app.dll, VCRUNTIME140_APP.dll and MSVCP140_APP.dll.
Test your exe inside the APPX folder to check that there are no complaints about the dll's.
Go back into Unity select UWP and then select build and run.

How to render many to many field data in Django template

I am able to render list of all courses and list of topics corresponding to the courses in different templates.
I need help to view list of all courses and when each course is clicked,a new page should show the list of associated topics
models.py
class Topic(models.Model):
topic_name = models.CharField(max_length=200, null=True)
topic_file = models.FileField(upload_to = "topic_file", blank=True, null=True)
def __str__(self):
return self.topic_name
class Course(models.Model):
course_name = models.CharField(max_length=200, null=True)
course_image = models.ImageField(upload_to="images", blank=True, null=True)
related_topic = models.ManyToManyField(Topic)
def __str__(self):
return self.course_name
Views.py
def view_course(request):
course_list = Course.objects.all()
context = {'course_list':course_list}
return render(request, 'upskill/view_course.html',context)
def course_topic(request,pk):
course_topic_list = Course.objects.get(id=pk)
var = course_topic_list.related_topic.all
context = {'var':var}
return render(request, 'upskill/course_topic.html',context)
Here is how you could get the related topics inside of a template.
{% for course in course_list %}
... data
{% for topic in course.related_topic.all %}
...data
{% endfor %}
{% endfor %}
If you don't want to do a query every single iteration of the {{course}} loop, I recommend you this in your views:
course_list = Course.objects.all().prefetch_related('related_topic')
And for a single object:
def course_topic(request,pk):
course = Course.objects.prefetch_related('related_topic').get(id=pk)
context = {'course ':course }
return render(request, 'upskill/course_topic.html',context)
And then in the template:
{{course.data...}}
{% for topic in course.related_topic.all %}
...data
{% endfor %}
To only have topics:
def topic_view(request, pk)
topics = Topic.objects.filter(course__pk=pk) #The reverse name of Course model.
# You can set a related name the "related_topic" field.
# Then access the above filter with that related name.
.... data
context = {
"topics":topics
}
return render(request, 'template.html', context)

In Django how to get specific user's data stored in profiles module

I am working on a project where I need to get some data into a chart but I don't know how to get the only data belongs to a specific user.
I am the Using original user modell that I extended with a Profile modell. I'm storing in the Profile a column called "csoport". I like to write a query where I get some other data from my "Kapcsolodasok" modell that joined to Profile modell.
I'm not so experienced in Django ORM so I'm using raw query.
HTML (just the query part)
{% for k in kapcsolodasok %}
{ id: "{{ k.user.get_full_name }}", label: "{{ k.user.get_full_name }}", group:{% for cs in csoport %}{{ cs.csoport }}{% endfor %} },
{% endfor %}
models.py
class Profile(models.Model):
def __str__(self):
return str(self.user)
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=1)
csoport = models.CharField(max_length=100)
class Kapcsolodasok(models.Model):
def __str__(self):
return str(self.user_name)
user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
kap_bar_01 = models.TextField(max_length=200)
kap_bar_02 = models.TextField(max_length=200)
...
class Projekt(models.Model):
def __str__(self):
return str(self.projekt)
projekt = models.TextField(max_length=150)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
views.py
#login_required
def project_details_report(request, projekt_id):
csoport = Profile.objects.raw('SELECT stressz_profile.projekt_id, stressz_profile.id, stressz_profile.id FROM stressz_profile INNER JOIN stressz_projekt ON stressz_projekt.id = stressz_profile.projekt_id WHERE stressz_projekt.id=%s', [projekt_id])
projekt = Projekt.objects.raw('SELECT projekt_id, id FROM stressz_profile WHERE stressz_profile.projekt_id=%s', [projekt_id])
kapcsolodasok = Profile.objects.raw('SELECT stressz_profile.id, kap_bar_user, kap_bar_01, kap_bar_02, user_name_id, projekt_id FROM stressz_kapcsolodasok INNER JOIN stressz_profile ON user_name_id = stressz_profile.user_id WHERE projekt_id=%s', [projekt_id])
context = {
'csoport': csoport,
'projekt': projekt,
'kapcsolodasok': kapcsolodasok,
}
return render(request, 'stressz/szervezeti_diagnozis.html', context)
The query work but it gives all the data of the csoport column. I need just the data from the csoport column that belongs to the specific user like this:
user: 1, csoport: orange
user: 2, csoport: lemon
user: 3, csoport: orange
Thank you for helping me in advance.
You access the Profile of the user with request.user.profile, you thus can print its .csoport with:
group: {{ request.user.profile.csoport }}
or if you want to use the .user of k, you can work with:
{% for k in kapcsolodasok %}
{ id: "{{ k.user.get_full_name }}", label: "{{ k.user.get_full_name }}", group: {{ k.user.profile.csoport }},
{% endfor %}

Querying ManyToMany fields in Django

I`ve got these defined models
class Occupation(models.Model):
title = models.CharField(max_length=150)
code = models.CharField(max_length=10)
what_they_do = models.TextField(blank=True, default="")
skills = models.ManyToManyField(Skill)
knowledge = models.ManyToManyField(Knowledge)
abilities = models.ManyToManyField(Ability)
technologies = models.ManyToManyField(Technology)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
Where Knowledge, Technology, Skill, Ability are similar. I have used this structure.
class Skill(models.Model):
title = models.CharField(max_length=64)
element_id = models.CharField(max_length=10)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
In my template , currently I have:
<ul>
{% for skill in ocuppation.skills.all %}
<li>{{skill.title}}</li>
{% endfor %}
</ul>
but {{ skill.title }} is blank.
In my views.py , I have defined this :
def detail(request, pk):
possible_occupation = Occupation.objects.filter(code=pk)
occupation = possible_occupation[0] if len(possible_occupation) == 1 else None
if occupation is not None:
context = {
'occupation': occupation
}
return render(request, 'careers/detail.html', context)
else:
return HttpResponseNotFound("No hay datos")
When I use the debugger I can see that occupation.skills, occupation.abilities ... are None.
If I check an occupation object in django admin , everything seems ok, but i can´t use them in templates.
Can anyone help?
Sorry for my bad english
You have misspelled occupation in your template.
{% for skill in ocuppation.skills.all %}
It should be
{% for skill in occupation.skills.all %}
Here's a tip for debugging next time. When the for loop didn't print anything, I would try to include the queryset I was looping over.
{{ ocuppation.skills.all }}
and if that didn't work, try the instance itself
{{ ocuppation }}
Then I would know that the problem is with the variable ocuppation, not the many to many field. Hopefully I would then spot the misspelling.

How to count how many posts each link has on a reddit-like app?

I have a reddit-like website where users post links and those links can be commented on. I want to display the number of comments under each link before being taken to the comment page for that link. What is the most query efficient way to do this in django that doesn't slow down the rendering of my site? I assume I'll have to go through a for loop of each link on the page to count the number of posts for each one and populate a list of some sort with the number returned from the .count() of each queryset? Here's what I have:
class Post(models.Model):
newlinktag = models.ForeignKey('NewLink', null=False)
childtag = models.ForeignKey('Post', blank=True, null=True)
postcontent = models.CharField(max_length=1024)
def __unicode__(self):
return self.postcontent
class NewLink(models.Model):
posttag = models.ForeignKey('PageInfo') #the page each link belongs to
linkcomment = models.CharField(max_length=512)
postlinkdate = models.DateTimeField(auto_now_add=True) #submission datestamp.
url = models.URLField(max_length = 1024)
linkowner = models.ForeignKey(User, null=True, blank=True)
def __unicode__(self):
return self.url
Jape gave you a good answer, but it is always more efficient to preform counting in the database rather than in python loops.
views.py
from django.db.models import Count
def view(request):
# Calculate the counts at the same time we fetch the NewLink(s)
links = NewLink.objects.annotate(post_count=Count('post_set'))
return render(request, 'template.html', {'links': links})
html
{% for link in links %}
{{ link.post_count }}
{% endfor %}
In your model, I would create a cached_property and then when you run the for loop in your template, call the property to get the count.
For example,
models.py:
class NewLink(models.Model):
posttag = models.ForeignKey('PageInfo') #the page each link belongs to
linkcomment = models.CharField(max_length=512)
postlinkdate = models.DateTimeField(auto_now_add=True) #submission datestamp.
url = models.URLField(max_length = 1024)
linkowner = models.ForeignKey(User, null=True, blank=True)
def __unicode__(self):
return self.url
# Might also want to flush this after a post_save method in your signals
#cached_property
def linkcomment_count(self):
return self.linkcomment.count()
views.py:
def view(request):
# Could do a 'select_related' relationship to save hits on the database
comments = NewLink.objects.all()
return render(request, 'template.html', {'comments': comments})
html:
{% for link in comments %}
{{ link.linkcomment_count }}
{% endfor %}
Did I understand your question correctly?

Categories