Django where autoblocks data is stored? - mysql

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?

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 %}

How to get the sum of a model field value from all the posts a user created in django base template?

I have a auth_user model, and a posts model. the posts model has fields like: id, author_id and likes. All I need print likes values related to each user in the base template. like:
{{ user.posts.likes }}
or
{{ user.user_id.posts.likes }}
This is my posts model:
class Post(models.Model):
title = models.CharField(max_length=150)
author = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.PositiveIntegerField(default=0, blank=True)
class Meta:
db_table = "posts"
def total_likes(self):
return self.likes
however it does not work, while {{ user.profile.image.url }} (profile is another model which has user_id) works perfectly.
I am importing base templates to other templates like {% extends "app/base.html" %} so I don't see any place in backend to pass the likes values
I believe the problem is that you're confusing a single Post for multiple posts and as a result there isn't an object to access. A user only has one profile, but as your code indicates they can have multiple posts as the author ForeignKey would indicate.
{{ user.post_set }} <- is a manager
{{ user.post_set.all }} <- is a queryset
{{ user.post_set.all.0 }} <- is the first item of the queryset
{{ user.post_set.all.0.likes }} <- should be the # of likes of the user's first post
Edit 1
The updated question could be restated as "how can I get the total number of likes a user has received via their posts"
There might be a way to accomplish that in the templates, but I think it's going to be difficult. I would put that number together in the view code. The key word that you're looking for is "aggregation"
https://docs.djangoproject.com/en/3.1/topics/db/aggregation/
from django.db.models import Sum
...
# inside your view
total_likes = user.post_set.all().aggregate(Sum('likes'))
Edit 2
Absolutely right #melvyn
Edit 3
In order to apply this to all pages without modifying the views you're going to have to write a context processor.
https://docs.djangoproject.com/en/3.1/ref/templates/api/#writing-your-own-context-processors
file: likes_context.py
from django.db.models import Sum
def likes_context_processor(request):
if request.user.is_authenticated:
posts = request.user.post_set.all()
total_likes = posts.aggregate(Sum('likes'))
else:
total_likes = 0
return {"total_likes": total_likes }
You'll need to locate that file appropriately and then add it to your context processors config in your settings.py
This might be helpful as well: creating my own context processor in django

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

Show Images Upload in Admin using FileField in Django

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 %}

Rebuilding Links with Django

I have created a Django app with the URL structure:
eventdetails/?event_id=94099
This would take me to the index page of the event details app. However My app has sections, and each section needs the event_id to use.
Therefore I need a url structure like:
eventdetails/who/?event_id=94099
So I can still access the event ID.
Could anyone advise me how to create the links for the navigation or a better way of doing this.
Thanks,
django's URL maps do not take into account the query string, which is passed as is to any view that is mapped.
In practical terms, this means that if you have:
url(r'^eventdetails/who/$', 'event_who', name='e-who'),
url(r'^eventdetails/$', 'event_detail', name='e-detail')
Then both your view methods will have access to the query string:
def event_detail(request):
id = request.GET.get('event_id')
def event_who(request):
id = request.GET.get('event_id')
if not id:
print 'No ID!'
else:
print 'do stuff'
return render(request, 'who.html')
You can also add the event id as part of the url itself, for example eventdetails/94099/:
url(r'^eventdetails/(?P<id>\d+)/$', 'event_detail', name='e-detail')
Then your views will be:
def event_detail(request, id=None):
if not id:
print 'No ID!'
else:
print 'do stuff'
return render(request, 'detail.html')
The other benefit you get is that you can easily generate URLs for your events in your templates and views:
<ul>
{% for event in events %}
<li> {{ event.name }}</li>
{% endfor %}
</ul>
In your view:
def go_to_event(request, id):
return redirect('e-detail', id=id)