How to get value from dropdown list in django - python

I am trying to create an application which gets date from a db and then gets input from the user and returns data for that specific user-input value. I am facing an error while doing this.
Views.py :
from django.shortcuts import render
from apple.models import predictions
from django.views.generic import View
# Create your views here.
def home_view(request):
return render(request, 'homepage.html')
def post(request):
company = str(request.POST.get("company-names"))
final_date = request.POST["date1"]
price = predictions.objects.filter(date=final_date)
for x in price:
pred = x.company
return render(request, 'results.html', {'price': pred})
def back_view(request):
return render(request, 'homepage.html')
Homepage.html :
<!DOCTYPE html>
{% extends "base.html" %}
{% block content %}
<html>
<body>
<div class="login">
<h1 id = "page-title">Predict Stock Prices</h1>
<h3 id = "date-title">Enter date (in format - yyyy-mm-dd)</h3>
<h3 id = "company-title">Choose Company</h3>
<form action="post" method="post">
{% csrf_token %}
<select name="company-names" id="company-names" selected="selected">
<option value="reliance">Reliance</option>
<option value="tcs">TCS</option>
</select>
<!-- <input type="text" id="company-names" name="company-names" placeholder="Company from Nifty-50"> -->
<input type="text" name="date1" placeholder="Date after ( 2020-02-18 )" id="date-form" />
<input type="submit" id="button-submit" value="Predict" />
</form>
</div>
</body>
{% endblock %}
</html>
Error I am getting :
Error
What my DB looks like :
DB

Related

Django: how to pass data from view to forms to validate it

In my form class I have a contact field in string to save several contacts separated by semicolons. In the request, contacts is an array so I do a ";".join(contacts) to get one contact field for my class form. I would like to pass this ";"join(contacts) contact from my view to the form class to validate it.
I simplified the code to focus on the part I have difficulties
the model class:
class Accounts(AbstractBaseUser):
phone_numbers = models.CharField(max_length=255))
the form class:
from django import forms
from .models import Accounts
import re
class RegisterForm(forms.ModelForm):
confirm_password = forms.CharField()
class Meta:
model = Accounts
fields = ('phone_numbers')
def clean_phone_numbers(self):
phone_numbers = self.cleaned_data['phone_numbers']
if len(phone_numbers) < 10:
raise forms.ValidationError('Your number must not be less than 10 digits')
if len(phone_numbers) > 15:
raise forms.ValidationError('Your number must not exceed 15 digits')
regex = '^[0-9]{10,15}$'
if not (re.fullmatch(regex, phone_numbers)):
raise forms.ValidationError('The number must not contain letters')
return phone_numbers
The view:
from django.shortcuts import render, HttpResponse
from .forms import RegisterForm
import logging
# Create your models here.
def register_user(request):
context = {}
if request.method == 'POST':
numbers = request.POST.getlist('phone_numbers')
numbers = ",".join(numbers)
form = RegisterForm(request.POST, phone_numbers=numbers) # Error
else:
form = RegisterForm()
context['form'] = form
return render(request, 'authentication/register.html', context)
the template:
<form action="#" method="post" novalidate>
<div id="number-composant">
<div class="form-group" id="input-field">
<label for="{{form.phone_numbers.id_for_label}}">Votre numero *</label>
<div>
{% if form.is_bound %}
{% if form.phone_numbers.errors %}
<input type="text" class="form-control is-invalid" id="{{form.phone_numbers.id_for_label}}" name="{{form.phone_numbers.html_name}}" value="{{form.phone_numbers.value}}" required>
{% else %}
<input type="text" class="form-control" id="{{form.phone_numbers.id_for_label}}" name="{{form.phone_numbers.html_name}}" value="{{form.phone_numbers.value}}" required>
{% endif %}
{% else %}
<input type="text" class="form-control" id="{{form.phone_numbers.id_for_label}}" name="{{form.phone_numbers.html_name}}" required>
{% endif %}
{% if form.phone_numbers.errors %}
<ul class="errorDetail">
{% for error in form.phone_numbers.errors %}
<li> {{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
<div>
<button type="button" class="btn btn-outline-primary-2 mt-1 mb-1" id="add-in"><span>Cliquez pour ajouter un autre numero <span class="ml-2">&plus;</span></span></button>
</div>
</div><!-- End .form-group -->
<script>
var i = 1
const MAX_LENGTH = 4
function remove(el){
document.getElementById('input-field').removeChild(el.parentNode.parentNode)
i--
}
function add(){
if(i<MAX_LENGTH){
div = document.createElement('div')
div.setAttribute('class', 'input-group mt-1')
html = ""
html += '<input type="text" class="form-control" placeholder="Un autre numero" name="{{form.phone_numbers.html_name}}">'
html += '<div class="input-group-append"><button type="button" class="btn btn-outline-primary-2" onclick="remove(this)"><span>&times</span></button></div>'
div.innerHTML = html
document.getElementById('input-field').appendChild(div)
i++
}
}
document.getElementById('add-in').addEventListener('click', add)
</script>
</div><!-- .End .tab-pane -->
</form><!-- End .form-box -->

How to run a python script like class in django?

I'm bit new with django and I'm lost, I don't know what to do. I'll explain what I want, maybe you can help me.
I want to create a web page on my site where you input your data and based on your data you get created a excel template which you download. Most basic, you input name of rows and columns and you download an excel document.
Here is what I have tried so far... I have a my_django folder and my_app folder, in my_app I'm trying to create an app to create templates.
This is my_app/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import TemplateForm
import xlsxwriter
from xlsxwriter import workbook
def home(request):
return render(request, 'my_app/home.html')
def create_template(request):
return render(request, 'my_app/create_template.html')
class CreateMyWebTemplate():
def create_template(doc_name, name_sheet, years, name_columns):
file = xlsxwriter.Workbook(doc_name + '_template.xlsx')
worksheet_data = file.add_worksheet()
worksheet_data.write_row(0, 1, years)
worksheet_data.write_column(1, 0, name_columns)
file.close()
return file
This is my_app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='my-home'),
path('create-template/', views.create_template, name='my-create-template'),
]
This is my_app/forms.py
from django import forms
class CreateMyWebTemplate(forms.Form):
doc_name = forms.CharField()
name_sheet = #selectedcountry
years = #listfromweb
name_rows = #imputed column names
This is my_app/template/my_app/create_template.html
{% extends "my_app/base.html" %}
{% block content %}
<div class="create-template-box">
<form action="/">
<h1>Create your template</h1>
<div class="item">
<p>Document name</p>
<div class="name-item">
<input type="text" name="doc_name" placeholder="Input document name without spaces" />
</div>
</div>
<div class="item">
<p>Select a country for the name of sheet</p>
<select name="name_sheet">
<option value="">Country</option>
<option value="1">Russia</option>
<option value="2">Germany</option>
<option value="3">France</option>
<option value="4">Armenia</option>
<option value="5">USA</option>
</select>
</div>
</div>
<div class="item" name="years">
<p>Select a years for columns</p>
<p> Start: </p> <select name="yearpicker" id="yearpicker"></select>
<br>
<p>End: </p> <select name="yearpicker2" id="yearpicker2"></select>
</div>
<div class="item">
<p>Please input a names of rows... seperate with commas</p>
<input type="text" name="name_rows"/>
</div>
<div class="btn-block">
<button type="submit" href="#">Create and Download!</button>
</div>
</form>
</div>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script type="text/javascript">
let startYear = 1800;
let endYear = new Date().getFullYear();
for (i = endYear; i > startYear; i--)
{
$('#yearpicker, #yearpicker2').append($('<option />').val(i).html(i));
}
$('select').on('change', function(){
let arr = Array.from({length:$('#yearpicker2').val() - +$('#yearpicker').val()},(v,k)=>k + +$('#yearpicker').val())
console.log(arr);
})
</script>
{% endblock content %}
In my_django app is included in settings.py and urls.py
For your create_template view, you can handle both HTTP GET and HTTP POST methods. You can also use Django's built-in form handling to make this so much easier.
New create_template.html
...
<form action="create_template" method="GET">
{% csrf_token %}
<h1>Create your template</h1>
<div class="item">
<table>
{{ form.as_table }}
</table>
</div>
<div class="btn-block">
<input type="button" type="submit" value="Create and Download!"/>
</div>
</form>
...
New content of views.py
from django.forms import Forn, CharField, ChoiceField, IntegerField,
...
class TemplateForm(Form):
name = CharField(label='Doc name')
choices=[('1', 'Russia'), ('2', 'Germany'), ('3', 'France'),
('4', 'Armenia'), ('5', 'USA')]
country = ChoiceField(label='name_sheet', initial='5', choices=choices)
choices = []
for year in range (2000, 2050):
choices.append( (year, year) )
year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices)
year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices)
columns = CharField(label='Column names')
def create_template(request):
if request.method == 'GET':
form = TemplateForm()
return render(request, 'my_app/create_template.html' form=form)
else:
form = TemplateForm(request.POST)
<use form inputs as needed>
...

retrive data according to the dropdown list item selected, in django

I have a dropdown list that is populated with "price range" from the database.
I want to show the relevant "price" according to the "Price Range"
for example, in the database, I have this row
Price Range Price
"0-1500" 28
"1501-1750" 30
What I want when I select the range "1501-1750" the corresponding "price" value shown in an input field or paragraph tag.
Below are my Model.py, views.py, and home.html files
models.py
from django.db import models
class price_range(models.Model):
name = models.CharField(max_length=100, null=False)
price = models.IntegerField(null=False)
views.py
from django.shortcuts import render
from range.models import price_range
def showobj(request):
displayvalues = price_range.objects.all()
return render(request, 'range/home.html', {"range":displayvalues})
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Range</title>
</head>
<body>
<center>
<select name="drop1">
<option selected disabled="true">Select the Price Range</option>
{% for results in range %}
<option> {{results.name}} </option>
{% endfor %}
</select>
</center>
</body>
</html>
This Question Helped me a lot in creating the logic for this problem.
[Django]How to return value to view after select item from dropdown list
views.py
from django.shortcuts import render
from range.models import price_range
def showobj(request):
selected_range = None
range_price = price_range.objects.all()
if request.method == "POST":
selected_range = request.POST.get("range")
range_price = range_price.filter(name=selected_range)
price = price_range.objects.order_by('name').values_list('name', flat=True)
context = {
'ranges': price,
'range_price': range_price,
'selected_range': selected_range,
}
return render(request, 'range/price_range.html', context)
price_range.html
<center>
<h1>Index</h1>
<form method="post">
{% csrf_token %}
{% if selected_range %}
{% for rest in range_price %}
<input name="price_value" value="{{ rest.price }}"></input>
{% endfor %}
{% endif %}
<select name="range">
<option selected disabled="true">Select the Price Range</option>
{% for range in ranges %}
<option value="{{ range }}" {% if selected_range == range %} selected="selected" {% endif %}>{{ range }}</option>
{% endfor %}
</select>
<input type="submit" value="Select">
</form>
</center>

How to return multiple photos directly to the current html page with flask

I want to create a function that shows the photos submitted by the user directly on the current page. In a nutshell, What i intended was to make kind of preview function that shows pictures in advance on the current page before the user finally uploads them.
I used pandas for buliding database, and photos are saved as the name of index number in static/img root.
I'm confused how to print out only the pictures that the user has just uploaded, out of the many pictures in the img folder.
flask__init__
#app.route("/apply", methods=['POST'])
def apply():
ctg = request.form.get('ctg_select')
if request.method == 'POST':
uploaded_files = request.files.getlist("file")
for f in uploaded_files:
f.save("helloflask/static/img/{}.jpeg".format(database.now_index()))
database.save(ctg)
return redirect(url_for('enroll', data_list=uploaded_files))
database
import pandas as pd
def save(ctg):
idx = len(pd.read_csv("database.csv"))
new_df = pd.DataFrame({"catagorize" : ctg},
index = [idx])
new_df.to_csv("database.csv", mode="a", header=False)
return None
def now_index():
df = pd.read_csv("database.csv")
return len(df)
HTML
{% extends "base.html" %}
{% block main%}
<h1 class="display-1" style="margin:20">Enroll your items</h1>
{% for img in data_list %}
<img src="" class="img-fluid" alt="...">
{% endfor %}
<form method="POST" enctype="multipart/form-data" action="{{url_for('apply')}}">
<input type="file" name="file" multiple="multiple">
<div class="form-floating">
<select name="ctg_select" class="form-select form-select-sm" aria-label=".form-select-sm example">
<option disabled selected value>Categorizes</option>
<option value="sports">Sports</option>
<option value="music">Music</option>
<option value="electronic">Electronics</option>
</select>
<label for="floatingSelect">Select categorize</label>
</div>
<label for="customRange3" class="form-label">Product status</label>
<input name="status_range" type="range" class="form-range" min="0" max="5" step="0.5" id="range">
<button type="submit" class="btn btn-secondary"> Submit </button>
</form>
{% endblock %}
database.csv
index, categories
0,electronic
1,electronic
2,electronic
3,electronic
4,electronic
5,electronic
6,electronic
7,electronic
8,electronic
9,electronic
10,electronic

how to search in mulit model using django

i want search from all my model in database , so i create this search functions for do this ... but always i got ' No results for this search '
how to fix this ?
view.py:
def search(request):
if request.method == 'GET':
query= request.GET.get('q')
submitbutton= request.GET.get('submit')
if query is not None:
home_database= Homepage.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
pcprograms_database= PCprogram.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
androidapk_database= AndroidApks.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
androidgames_database= AndroidGames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
antiruvs_database= Antivirus.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
systems_database= OpratingSystems.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
pcgames_database= PCgames.objects.filter(name__icontains=query,app_contect__icontains=query,page_url__icontains=query,app_image__icontains=query)
results= list(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database))
context={'results': results,
'submitbutton': submitbutton}
return render(request, 'html_file/enterface.html', context)
else:
return render(request, 'html_file/enterface.html')
else:
return render(request, 'html_file/enterface.html')
html search form :
<form id="search_form" action="{% url 'search' %}" method="GET" value="{{request.GET.q}}">
<input id="search_box" type="text" name="q" value="{{request.GET.q}}"
placeholder=" Search For ... "/>
<input id="search_button" type="submit" name="submit" value="Search"/>
</form>
html file :
{% if submitbutton == 'Search' and request.GET.q != '' %}
{% if results %}
<h1> <small> Results for </small><b>{{ request.GET.q }}</b> : </h1>
<br/><br/>
{% for result in results %}
<label id="label_main_app"> <img id="img_main_app_first_screen" src="{{result.app_image.url}}" alt="no image found !" height="170" width="165" > {{result.name}} <br><br> <p id="p_size_first_page"> {{result.app_contect}} <br> <br> <big> See More & Download </big> </p>
</label>
{% endfor %}
{% else %}
<h3> No results for this search </h3>
{% endif %}
{% endif %}
any help please ?
If you are trying to filter with multiple model fields you need Q from django.db.models
Homepage.objects.filter(Q(name__icontains=query)&Q(app_contect__icontains=query),....

Categories