Show Images Upload in Admin using FileField in Django - html

I need to show multiple images uploaded in the Admin page (using FileField) in my html.
I'm currently using:
Python 3.6.0b4
Django 1.10.3
I can currently show if the model only has one image but when I try to put multiple images, I have no idea how to show it.
Here is my code:
models.py
class Product(models.Model):
name = models.CharField(max_length=140)
created_by = models.ForeignKey(User,null=True)
def __str__(self):
return self.name
class ProductImage(models.Model):
name= models.ForeignKey(Product)
image = models.FileField(upload_to='media/',null=True,blank=True)
admin.py
class ProductImageInline(admin.TabularInline):
model = ProductImage
class ProductModelAdmin(admin.ModelAdmin):
exclude = ('created_by',)
inlines = [ProductImageInline]
def save_model(self, request, obj, form, change):
if not change:
obj.created_by = request.user
obj.save()
admin.site.register(Product,ProductModelAdmin)
If I add
image = models.FileField(upload_to='media/',null=True,blank=True)
in my model.py, I can show it in the html like this:
<img width=200 src="{{product.image.url}}" /></a>
How can I show the Multiple Images in the html?
I'm fairly new to Django but have experience on web development.
Thanks in advance.

If you have many-to-one relation you can get all related to the object records using <modelname>_set property.
So try iterate through all images in productimage_set:
{% for image in product.productimage_set.all %}
<img src="{{image.image.url}}">
{% endfor %}

Related

Django: Read image path field from MySQL

im curently making a mini product eshop for my studies. So I have the image path of products in MySQL database like LOAD_FILE(C:\\product.jpg) and I want to access the image from my Django project.
I have 2 questions. 1st, what Model Field should I use to read the image from the database's image path. And 2nd one how to read this image?
class Product(models.Model):
name = models.CharField(max_length=200, null=True)
price = models.DecimalField(max_digits=7,decimal_places=2)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
The Models.ImageField is perfect for this. You don't need to it like this. Simply get your image in the template using {{ Product.image.url }} inside an img tag. Use If condition in templates such as {% if Product.image.url is not null %} <Show the picture> {% else %}<show some default image or show some text> {% endif %}

Can't call model to Django template

I'm trying to call an attribute from my model into my HTML template using Django. There is something strange going on as I am only able to call one of my two models into the template. Both models are working perfectly fine as far as I can tell by looking into my database. This is what my models.py looks like
class Respondez(models.Model):
responder = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='scores')
score = models.IntegerField(default=0)
post_time = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['post_time']
def __str__(self):
return self.score
class Profilez(models.Model):
newuser = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True,null=True)
preference = models.CharField(max_length=30)
def __str__(self):
return self.newuser
I am trying to call Profilez. However, only Respondez can be called. This is the view I'm calling from, which I simplified.
#login_required
def add(request):
p = Profilez()
z = Respondez()
context = {
'p' : p,
'z' : z
}
return render(request, 'rating/add.html', context)
To test whether I can call my models, I have simple header tags in HTML for my template, add.html:
{% extends "rating/base.html" %}
{% block content%}
<h3> {{user.username}} </h3>
<h3> {{ z.post_time }}</h3>
<h3>{{ p.preference }}</h3>
No matter which attribute I call from the models, the line for Respondez works but nothing works for my Profilez model. This is despite the fact that my database has values saved for each attribute from both models.
I am getting inputs for preference from the following view on a separate template (first line won't paste with correct indentation), where users select 1 of 2 choices:
def onboarding2(request):
p = Prof()
p.newuser = request.user
if request.method == 'POST':
selected_opt = (request.POST['ob'])
if selected_opt == 'mood':
p.preference = 'mood'
elif selected_opt == 'productivity':
p.preference = 'productivity'
else:
return HttpResponse(400, 'Invalid form')
p.save()
return redirect('rating-onboarding3')
context = {
'p' : p,
}
return render(request, 'rating/onboard2.html', context)
How can I accurately call my Profilez model? What's wrong here?
Since you have instantiated Profilez with no parameters in the constructor, none of its fields get the initial value. Hence, p.preference also happens to be null. That is why p.preference is not visible in the template.
But, in case of Respondez, though you are still instantiating the object with no parameters, you still have given the default value of current time to z.post_time, so z.post_time is working.
If you want to access p.preference, you need to explicitly assign some value to p.preference, else how will the template show the value for something that doesn't have a value initialized in the first place? For instance, you could do p = Profilez(preference='xyz') while creating the object, and see what happens.
Also, if you want to fetch a specific entry from the database, then you need to do a query, rather than creating a new object. The syntax for creating query would be something like Profilez.objects.get(newuser=some_random_user).

How can i pass my data in sqlite database to templates? ( to make line chart using highcharts)

i'm developing web application using dJango.
My current situation is as below
When users do something, the data is saved into sqlite database
I want to pass my data to templates and draw line chart
I want X-axle : YYYY-MM-DD / Y-axle : the count of request
But, i have no idea how to make it.
{{ addRequestCnt }} is presented like as below.
"QuerySet [{'doDate':datetime.datetime(2019,4,15,0,0),'requestType__count':11}, {'doDate':datetime.datetime(2019,4,16,0,0),'requestType__Count':7}]>"
......
Thank you for helpful answer in advance.
My models.py
class ActivityLog(models.Model):
doDate = models.DateTimeField()
requestType = models.CharField(max_length=200)
My views.py
def dashboard(request):
addRequestCnt = ActivityLog.objects.filter(requestType='add').values('doDate').annotate(Count('requesetType'))
context = {
'addRequestCnt':json.dumps(addRequest, default=str),
}
return render(request,'dashboard.html',context)
Here is an example of a blog post model, our database schema
Here is how to return the data to the template a list view
And here is how to return data to the detail view
What you want on your template based on your model is something like this:
{% block content %}
<div class='col-sm-6 col-sm-offset-3'>
<h1>{{ doDate }}</h1>
<h2><small>{{ requestType }}</small></h2>
{% endblock content %}
Here is the official documentation for Django templates

Django where autoblocks data is stored?

I am working on online shop project. I have product model and it has description field, but it's empty. Description data is stored somehow with django-cms and autoblocks. I can edit that description in browser with django-cms. In the template this {% autoblock product.slug %} line is description.
In views.py, i pass product as context, but it's slug field has nothing to do with description, when i try {{ product.slug }}.
Also googled about Autoblocks, but only what managed to find out it's this model:
class Autoblock(models.Model):
composite_id = models.CharField(max_length=150)
content = PlaceholderField('content')
site = models.ForeignKey(Site)
def __unicode__(self):
return self.composite_id
All of these fields has nothing to do with description.
So my question is, how can i access that description in code?

Django 1.6 Getting data from two models into one view

Have two models and need to get them both out on one page at the same time. I know I need one view with the two models under it.
lol
heres what I got:
def inventory(request):
products = Product3.objects.all()
productinfo = {
"product_detail": products
}
return render_to_response('inventory.html', productinfo, context_instance=RequestContext(request))
def itemdetailpage(request, id):
property = Product3.objects.get(pk=id)
property1 = property.images.all()
itemin = {"itemdetail": property1 }
return render_to_response('details.html', itemin, context_instance=RequestContext(request))
How do I get these data into one view? so I can display both of their contents in one template, with the arguments part of itemdetail page code.?
Solution in the view has been as follows:
I figured this out about an hour after I posted this and thank you Dan for the responding and are absolutely right everything was there:
def itemdetailpage(request, id):
property = Product3.objects.get(pk=id)
property1 = property.images.all()
itemin = {'property': property, 'imagedetail': property1}
return render_to_response('details.html', itemin, context_instance=RequestContext(request))
You have all the information you need already. You know how to get the images related to an item, with product.images.all(). You can simply do that in the template, as you iterate through the products; you don't need the second view at all.
{% for product in products %}
{{ product.name }}
{% for image in product.images.all %}
{{ image.image }}
{% endfor %}
{% end for %}
If you absolutely need both views, you could make AJAX calls to update your page content. If you're free to change the code, why not return all needed data from one of both views?
Side note: You should make your code more readable.