DJango How to select certain item from database table in html - python

I have a store page that gets entries from a Products table.
This shows products in order in the same format infinitely for how many are in the table.
`
{% for product in products %}
<div class="container2">
<div href="item" class= 'product-item'>
<div class= 'image-cont'>
<img class='product-image'src = '{{product.product_picture.url}}' alt="" >
</div>
{% if product.offer != 0 %}
<div class= 'offer-banner' >
Special Offer
</div>
{% endif %}
</div>
<div href="item" class="product-content">
<div href="item" class="product-title">
<a href="item" >{{product.name}}</a>
</div>
<div class="product-price">
<a href="item" >${{product.price}}</a>
</div>
<br>
<div class="product-desc">
<a href="item" >{{product.desc}}</a>
</div>
<br>
<div class="product-userpfp">
<a href="#" ><img src='{{product.userpfp.url}}'></a>
</div>
<br>
<div class="product-poster-name">
<a href="#" >{{product.username}}</a>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
`
I want to be able to click on any product from products and get a page with the specific item I clicked on. This is my Item page.
`
{`% extends 'base.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" href= "{% static 'css\item.css' %}" >
{% endblock %}
{%block content%}
{% load static %}
<h1>Item</h1>
<h3>{{item.name}}</h3>
{% endblock %}`
`
The problem should be inside the view.py file
`
def item(request):
item = Product.objects.select_related()
return render(request, "item.html", {"item": item })
def store(request):
products = Product.objects.all()
return render(request, 'store.html', {'products': products}) ;
`
The store function works. But the item function is not working. My guess is that the 'select_related' may not be the correct tool to use.
I tried changing the select_related tool to a few different ones but was worried I would ruin my table somehow so I am seeking help, Thank You.

Assuming that you are passing product_id to the item page when a product is clicked, you need to pass that product_id to the item function and rewrite the code as,
def item(request):
item = Product.objects.select_related('item').get(id=product_id)
return render(request, "item.html", {"item": item })

Related

Python+Django - can't see my product image, name and price when I do those changes :

I have this code
<div style="flex:2"><img class="row-image" src="{% static 'images/placeholder.png' %}"></div>
<div style="flex:2">Product 1</div>
<div style="flex:1">$20</div>
<div style="flex:1">
<p class="quantity">2</p>
and made those changes :
static 'images/placeholder.png' to {{item.product.imageURL}}
Product 1 to {{item.product.name}}
$20 to ${{item.product.price|floatformat:2}}
2 to {{item.quantity}}
views
models
There is a typo in your model OrderItem field prouct. Please fix it or do this change in your template cart.html
{% for item in items %}
<div style="flex:2"><img class="row-image" src="{{item.prouct.imageURL}}"></div>
<div style="flex:2">{{item.prouct.name}}</div>
<div style="flex:1">${{item.prouct.price|floatformat:2}}</div>
<div style="flex:1">
<p class="quantity">{{item.quantity}}</p>
</div>
{% endfor %}

How to pass Data to Flask_Admin's View's HTML?

I'm currently trying to populate widgets on the Flask_Admin Home Page with data from my Database.
However, I'm having trouble passing the data into the HTML. Here is my view, where I want to render accountBalance:
class MyView(BaseView):
accountBalance = 0
#expose('/')
def index(self, accountBalance, **kwargs):
self.accountBalance = accountBalance
return self.render('admin/index.html', accountBalance=accountBalance)
# And app code:
accountBalance = 10000
if __name__ == '__main__':
admin = Admin(app, name='MyAdmin', template_mode='bootstrap3')
admin.add_view(views.MyView(accountBalance))
app.run(host='0.0.0.0')
And here's the HTML/Jinja logic in admin/index.html, which tries to render the accountBalance I passed in above:
{% extends 'admin/master.html' %}
{% block head_css %}
{{ super() }}
<link href="{{ url_for('static', filename='sb-admin-2.css') }}" rel="stylesheet">
{% endblock head_css %}
{% block body %}
{{ super() }}
<div class="col-lg-3 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-comments fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">This is your balance:</div>
<div> {% accountBalance %}</div>
</div>
</div>
</div>
</div>
</div>
{% endblock body %}
I've been following examples to try to get this to work, where the '{% accountBalance %}' in the HTML should be the value of accountBalance I'm trying to pass in, but to no prevail.
What am I doing wrong?
Use {{ accountBalance }}. {% .. %} is used for statements like for loop and if conditions.
From the documentation:
{% ... %} for Statements
{{ ... }} for Expressions to print to the template output

linking search results to a its own detail page

This is a django related question:
I am doing an assignment where we are playing around making a search bar then afterwards letting each individual search result linked to its own page with more details. In this context we are doing a job search engine and I need assistance in when you click each jobs posting, it takes you to a separate page with more info about the job. We already made templates for all the pages. I understand that we have to make a request to the api again after doing it for the view function in the search bar and also use templating got fill up out the detailed search results.Im just not sure how would I apply these concepts to the html file that w ehave.
here's the code
View function code
import requests
from django.shortcuts import render
def home(request):
context = {
'example_context_variable': 'Change me.',
}
return render(request, 'pages/home.html', context)
def search_results(request):
search_query = request.GET['searchterm']
context = {
'result_count': 0,
'search_term': search_query,
}
context['results_count'] = 0
url = 'https://jobs.github.com/positions.json?location=bay+area&description='
url += search_query
response = requests.get(url)
results_data = response.json()
job_list =[]
for result in results_data:
job_list.append(result)
context['job_results'] = job_list
return render(request, 'pages/search_results.html', context)
Search Results Page
{% extends "base.html" %}
{% block title %}
Search Results
{% endblock title %}
{% block additional_styles %}
<style>
body {
background-color: white;
}
</style>
{% endblock %}
{% block content %}
<div id="home-content" class="container">
<div class="row">
<div class="col-lg-3"></div> <!-- Column for spacing -->
<div class="col-lg-6">
<div class="mt-5 mb-3 text-center">
<h1>Search Results</h1>
</div>
<form method="GET" action="/search-results/">
<div class="input-group mb-2">
<input name="searchterm" type="text" class="form-control form-control-lg" placeholder="Let's find a job..." />
<div class="input-group-append">
<button class="btn btn-primary btn-lg">Search</button></a>
</div>
</div>
</form>
<!-- 2start -->
<p>You Searched for: {{search_term}}</p>
{% for job in job_results %}
<div class="list-group">
<a href="/detailed-search-results/" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{job.title}}</h5>
</div>
<div>
<small class="text-muted">{{job.location}}</small>
</div>
</a>
</div>
<br>
{% endfor %}
<!-- End -->
{% endblock content %}
**detailed Search Results Html file **
So far when you click on a posting it takes you to the detailed search result page without anything on it.
That is because you have hyperlinked each job posting to /detailed-search-results/.
Looking at the API response, you need to change it to job.url
Replace your for loop with this:
{% for job in job_results %}
<div class="list-group">
<a href="{{ job.url }}" class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{job.title}}</h5>
</div>
<div>
<small class="text-muted">{{job.location}}</small>
</div>
</a>
</div>
<br>
{% endfor %}

How to loop though user objects in django

I want to show all the user's Items.
Currently I can only show 1 object
my_items.html (where i want it to show)
{% extends 'base.html' %}
{% block content%}
<main role="main">
<div class="container">
<!-- Example row of columns -->
<div class="row">
{% for item in item %}
<!--{% if item.id == request.user.id %}-->
<div class="col-md-4">
<div class="col-md-4">
<img style="max-width: 100px; max-height: 300px" src="{{ item.thumb.url }}">
</div>
<h2>{{ item.name }}</h2>
<p>{{ item.snippet }}</p>
<p>{{ item.date }}</p>
<p><a class="btn btn-warning" href="#" role="button">Edit</button></a></p>
<p><a class="btn btn-danger" href="#" role="button">Delete</a></p>
</div>
<!--{% endif %}-->
{% endfor %}
</div>
<hr>
</div> <!-- /container -->
</main>
{% endblock %}
views.py
def item_myitems(request):
item = Item.objects.all().order_by('date')
return render(request, 'items/my_items.html', {'item': item})
I tried using filter() and get() on views.py
You should use a plural name to pass your items to your view:
def item_myitems(request):
items = Item.objects.all().order_by('date')
return render(request, 'items/my_items.html', {'items': items})
So you can distinguish one item from many items when you loop through them in your view:
{% for item in items %}
omg I got it working, i feel so dumb right now LOL
I uncommented my if in the html and set to this > {% if item.author_id == request.user.id %} i was comparing with the item id instead of the author_id

How do I hide or show content for each iteration?

I have a Lecture model which contains lectures. For each lecture I have a title and a content and eventually some files. I was trying to make that when somebody presses on a title, the title and the content will display under, but only for that lecture. Problem is that if I use a class, all lectures will be shown and if I use and id only the first one will be shown. How should I do this ?
$('#title').click(function () {
$('#lecture-hide').toggle();
});
{% for c in category.list %}
<div id="title">
<p>Lecture {{ forloop.counter }}: <span>{{ c.lecture_title }}</span>
</p>
<br>
</div>
<div id="lecture-hide" style="display: none;">
<br>
<li><h5>{{ c.lecture_title }}</h5></li>
<li><p>{{ c.content }}</p></li>
{% for file in c.files.all %}
{% if file.files %}
{% if forloop.first %}
<p id="files">Lecture files:</p>
{% endif %}
<li><a class="media"
href='{{ MEDIA_URL }}{{ file.files.url }}'><i
class="fas fa-download"></i>{{ file.files.name }}</a></li>
{% endif %}
{% endfor %}
<br>
</div>
{% endfor %}
Maybe you can use next selector in your jQuery code like this:
$('div.title').click(function () {
$(this).next().toggle();
});
You have to change id of the title to class to apply this to every element of the list.
You need to set dynamic attributes in your html:
{% for c in category.list %}
<div class="title" id="title-{{ c.id }}">
<!-- the content -->
</div>
<div class="lecture-hide" for="title-{{ c.id }}" style="display: none;">
<!-- the content -->
</div>
{% endfor %}
and in JQuery
$('.title').click(function () {
$('.lecture-hide[for="title-' + $(this).attr('id') + '"]').toggle();
});
This will works even if the html elements order change.

Categories