A Simple Calculator using Django - python-3.x

I want to create a website where the user is asked to type a given number to get the square number and the square root.
This is from index.html:
<div class="d-flex typeW">
<form action="add">
Enter a number : <input type="text" name="num1">
<input type="submit">
</form>
</div>
This is from the result page (where you can see the result):
<div class="d-flex title2">
<h2>
{% block content %}
{{result}}
{% endblock %}
<br><br>
This is from view:
def add(request):
num1 = int(request.GET["num1"])
return render(request, 'result.html' , {result2: num1 * num1})
Now I want to take the square root of that number but I'm not sure how.
How do I take one input and then do two calculations by using two functions?
help much appreciated

Simply do two calculations in your view and return both results within the context. You can then access all values in the context and render them in the template.
import math
def add(request):
# Get the user input
num1 = int(request.GET["num1"])
# Calculate square
num1_square = num1 ** 2
# Calculate root
num1_root = math.sqrt(num1)
# return context
context = {
'square': num1_square,
'root': num1_root
}
return render(request, 'result.html' , context)
# template
<div class="d-flex title2">
<h2>
{% block content %}
{{ square }}
{{ root }}
{% endblock %}
<br><br>

Related

Display selection field in Django template

I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this:
from django.db import models
class Consumer(models.Model):
SIZES = (
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
)
name = models.CharField(max_length=60)
size = models.CharField(max_length=2, choices=SIZES)
And I did in my view and template like this (Learned from one tutorial)
***view with combined queries***
def staff_filter(request):
qs = Consumer.objects.all()
size= request.GET.get('size')
# I have some other queries in between ....
if is_valid_queryparam(size) and size!='Choose...':
qs = qs.filter(size=consumer.get_size.display())
return qs
def filter(request):
qs=staff_filter(request)
context={
'queryset':qs,
'consumer':consumer.objects.all()
}
return render(request, 'filter.html',context)
**template***
<div class="form-group col-md-4">
<label for="size">size</label>
<select id="size" class="form-control" name="size">
<option selected>Choose...</option>
{% for size in consumer.get_size.display %}
<option value="{{ size }}">{{size}}</option>
{% endfor %}
</select>
</div>
How should I correct it? Thanks!
Display selection field in Django template
You mispelled consumer in context in view
'consumer':consumer.objects.all() #You mispelled consumer here
Try this:
'consumer':Consumer.objects.all() # Consumer, first letter should be capital
I think you misplelled in above code so that's why you are not getting values on template
You do not need any get_size.display() method in a template. If consumer variable is an object of the Consumer class then you just have to do like this:
<select>
{% for val, text in consumer.SIZES %}
<!--
Here SIZES is a tuple variable of your Consumer class,
while consumer is an instance of the Consumer class then you can just
call SIZES tuple from any of its instances.
-->
<option value="{{ val }}">{{ text }}</option>
{% endfor %}
</select>
If consumer is a variable from the context you are passing in your
view, then it's a queryset. So in this case you should loop over your queryset first, then call SIZES variable from every object inside the loop:
{% for object in consumer %}
<select>
{% for val, text in object.SIZES %}
<option value="{{ val }}">{{ text }}</option>
{% endfor %}
</select>
{% endfor %}

Is there any way to iterate over list inside list in django template?

I have a list a = [[1000,3000], [4000-5000]], i would like to show it has
1000-3000
4000-5000 in template. But i'm getting only the first object.
What i tried is,
products.html
{% for i in price_group %}
<label>
<input class="uk-radio" type="radio" onchange="$('#form').submit();" name="price" value="{{ i.0.0 }};{{ i.0.1 }};price;first" checked>
{{ i.0.0 }} - {{ i.0.1 }}
</label>
{{ price_group.pop.i }}
{% endfor %}
I used pop functionality to remove current from the list and take the next one, but it's not working as expected.
it is showing only the first element in the list. Please correct me if I am wrong. What I want is it has a price range like.
1000-3000
4000-5000..like wise. Please help me.
You are accessing only first element of the list, you need to update your code to access all the elements like this:
{% for i,j in price_group %}
<label> <input class="uk-radio" type="radio" onchange="$('#form').submit();" name="price" value="{{ i }};{{ j }};price;first" checked>
{{ i }} - {{ j }}
</label>
{% endfor %}

Is there a way to programmatically have 4 cards per row?

I am currently working with Python Flask and Bootstrap.
I am looking to get it so that if there are 4 cards in one row, it will automatically create a new row.
Issue i am having just now is the more posts I have the longer and thinner the rows cards get.
Current code:
{% extends "base.html" %}
{% block content %}
<div class="card-deck">
{# Go through each forum post #}
{% for post in forum_posts.items %}
<div class="card">
<div class="card-body">
<span class="badge badge-info">{{ post.cat }}</span>
<h3 class="card-title"><a class="card-title"
href="{{ url_for('forum_posts.view_post', forum_post_id=post.id) }}">{{ post.title }}</a>
</h3>
<h6 class="card-subtitle mb-2 text-muted">Written by: {{ post.author.username }}</h6>
<p>{{ post.text[:100] }}...</p>
</div>
<div class="card-footer">
<a href="{{ url_for('forum_posts.view_post', forum_post_id=post.id) }}"
class="btn btn-primary">Read
Blog Post</a>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
You could code this on the python side so that it makes it easier in jinja2, using an array of arrays:
>>> arr = [0,1,2,3,4,.....,102]
>>> forum_posts.items = []
>>> for i in range(int(len(arr)/4)):
j = i * 4
forum_posts.items.append([arr[j], arr[j+1], arr[j+2], arr[j+3]])
# needs an error trap for IndexError on 103
Then in jinja2: you can double loop:
{% for row in forum_posts.items %}
{% for item in row %}
{# HTML here for a new row of at most 4 cards #}
There is a way of doing the same kind of thing in jinja2 using variable loop counters and setting new row HTML if for example the new loop index is an exact multiple of 4:
{% for i, post in enumerate(forum_posts.items) %}
{% if i % 4 == 0 %}
{# new row code #}
{% else %}
{# regular row code %}
{% endif %}
{% endfor %}

Create a comment section in flask

Im working on the comment section of my page and found a useful website with this https://blog.miguelgrinberg.com/post/implementing-user-comments-with-sqlalchemy. The problem i am having is representing the comments on the website. How to i display nested comments in the same manner as shown in the link above using the flask code below.
for comment in Comment.query.order_by(Comment.path):
print('{}{}: {}'.format(' ' * comment.level(), comment.author, comment.text))
In other words: how would the above segment look as jinja code.
{% for comment in comments %]
.
.
.
{% endfor %}
If there is another way to do it, i'm all ears. Thanks.
Here i am after some research and successful completion of my comment section to answer my own question. To get this effect do this below
{% for comment in all_comments %}
<div class="row">
{% if comment.comment_level == 0 %}
<div class="col-lg-12 ">
{% elif comment.comment_level == 1 %}
<div class="col-lg-1 "></div>
<div class="col-lg-11">
{% elif comment.comment_level == 2 %}
<div class="col-lg-2 c"></div>
<div class="col-lg-10 ">
{% elif comment.comment_level == 3 %}
<div class="col-lg-3 "></div>
<div class="col-lg-9 ">
{% else %}
<div class="col-lg-4 "></div>
<div class="col-lg-8 ">
{% endif %}
<div>
<p>{{comment.text}}</p>
</div>
This will create the step ladder effect you see in comment section. This is a flask solution. I'm sure you can replicate it in other languages.

If statement in Twig (for Particle in Joomla)

Trying to edit a particle in Joomla -- I'm fairly new to twig and I'm trying to list information based on a selection in vertical tabs. I have an on-click refresh for my li edit that makes a tab "selected" and creates my internal url:
{% for item in particle.items %}
<li>
<a href="/Joomla/about-the-library/locations#{{ loop.index }}">{{ item.title|e }}
<img src="{{ url(item.image)|e }}" alt="{{ item.title|e }}">
<div class="g-flexslider-carousel-item-image-preview-icon"></div>
</a>
</li>
{% endfor %}
This is all well and good, but I ran into an issue when trying to display the data associated with the selected item. I tried to create a variable to check my items against, but the variable doesn't seem to be coming back as an integer, and I've tried a few things:
{% set branch = app.request.pathinfo|trim('/Joomla/about-the-library/locations#') %}
{% if loop.index == branch %}
<div class="g-flexslider-showcase-item-content-container">
<div class="g-flexslider-showcase-item-image">
<img src="{{ url(item.image)|e }}" alt="{{ item.title|e }}">
</div>
Can anyone tell me what I'm doing incorrectly?
(I found that get current url in twig template? helped, but I'm not sure I'm using the answers provided correctly. I've also sifted through the Twig Documentation for a couple hours to no avail.)
[Nov 2016] - This is still what "my" code looks like for this section. It seems to just be a problem with this if statement, as the "else" statement (which I'm using for debugging purposes) keeps coming through.
{% for item in particle.items %}
{% if app.request.get('name') == item.URLname|e %}
<p>You have branched {{ item.title|e }} correctly. </p>

Resources