Rebuilding Links with Django - html

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)

Related

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

See all the items created by the logged in user

novice here trying to get an ebay style e-commerce project finished!
When a user checks their profile, I want it to list all the items they have for sale. The owner in the Item model stores the username, so, essentially, I want to check the owner field of all items, then pull the ones that are == username.
Here's the code I got so far:
views.py
def user_profile(request):
"""The users profile page"""
user = User.objects.get(email=request.user.email)
user_items = Item.objects.filter(owner__icontains=request.GET[user])
return render(request, 'profile.html', {"profile": user, "items": user_items})
I'm then using {% for item in user_items %} in the html.
Apologies if this is an easy one, but I'm struggling to get this right.
# request.user.username is your logged in user, so you have to filter your owner field with request.user.username
def user_profile(request):
"""The users profile page"""
user = User.objects.get(email=request.user.email)
user_items = Item.objects.filter(owner__icontains=request.user.username)
return render(request, 'profile.html', {"profile": user, "items": user_items})
# In your template, you have to use:-
{% for item in items %}
{{item.field_name}}
{% endfor %}

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.