How to run a python script like class in django? - python

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>
...

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

Django POST request parameters returns none in views.py

I want to take values from a POST request. I want to take "taken_name" value from html form to views.
I tried several question's answers, but I think I' m missing very simple thing. I can not figure it out nearly 2 hours.
Parameter name in html is 'taken_name'.
Also urls and views parameters are true and matching with the methods which mentioned on stackoverflow.
I' m getting this error :
'null value in column "visitor_name" of relation "visitor" violates
not-null constraint DETAIL: Failing row contains (15, null, null,
null).'
This means I can't get the value from html.
Tried:
get value from POST request in Django
res.html
{% for i in allList %}
<div id="createRecordModal-{{forloop.counter}}" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="/session/{{visitor_id}}">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title" name="taken_table">Masa {{i.table_number}}</h4>
<button
type="button"
class="btn-close btn-close-white"
data-bs-dismiss="modal"
aria-hidden="Close"
></button>
</div>
<div class="modal-body">
<div class="form-group">
<label>İsim</label>
<input
name="taken_name"
type="text"
class="form-control"
required
/>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
aria-label="Close"
>
İptal
</button>
Kaydet
</div>
</form>
</div>
</div>
</div>
{% endfor %}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.loginUser, name="login"),
path('reservation', views.reservation, name="reservation"),
path('delete/<str:table_number>', views.delete, name='delete'),
path('create/<str:table_number>', views.create, name='create'),
path('session/<str:visitor_id>', views.createSession, name='create2')
]
views.py
def createSession(request, visitor_id):
addSession = visitor.objects.filter(visitor_id = visitor_id)
if request.method == "POST":
taken_name = request.POST.get('taken_name')
taken_surname = request.POST.get('taken_surname')
taken_time = request.POST.get('taken_time')
print(taken_name)
print(taken_surname)
print(taken_time)
else:
print('method is not POST')
addSession.create(
visitor_name = taken_name,
visitor_surname = taken_surname,
res_time = taken_time
)
context = {
'addSession': addSession
}
return redirect('reservation')
def reservation(request):
allList = table_inventory.objects.all()
max_rating = table_inventory.objects.aggregate(Max('table_number')).get('table_number__max')
visitor_no = visitor.objects.aggregate(Max('visitor_id')).get('visitor_id__max')
visitor_no +=1
return render(request, 'reservation.html', {
'allList': allList,
'max_rating': max_rating,
'visitor_no': visitor_no
})
In your template, you are using the following:
Kaydet
If you were intending to use this to submit your form, it won't work. It will simply link to the URL nominated in the href attribute.
Try something like:
<button type="submit" class="btn btn-danger">Kaydet</button>

How to get value from dropdown list in django

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

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

django form wizard - NoReverseMatch - looking for a specific named step

I'm trying to setup a multi-step form using Django Form Wizard, but running into a "NoReverseMatch" error.
From previous experience with this error, it was because I was not passing through an argument when the url takes one, i.e. (?P<pk>\d+).
In my specific case:
Reverse for 'task_step' with arguments '()' and keyword arguments '{'step': u'address'}' not found. 0 pattern(s) tried: []
What I've tried so far:
passing wizard.steps.current in the <form action="">
passing wizard.steps.next in the <form action="">
Is it something to do with my urls.py?
// views.py
FORMS = [("subcategory", ChooseSubcategoryForm),
("address", SetAddressForm),
("task-details", AddTaskDetailsForm),]
TEMPLATES = {"subcategory": "tasks/create_task_form/step1.html",
"address": "tasks/create_task_form/step2.html",
"task-details": "tasks/create_task_form/step3.html",
}
class AddTaskWizard(NamedUrlSessionWizardView):
form_list = [ChooseSubcategoryForm, SetAddressForm, AddTaskDetailsForm]
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def get_context_data(self, form, **kwargs):
context = super(AddTaskWizard, self).get_context_data(form=form, **kwargs)
# add extra variables for a specific step
# if self.steps.current == "step_name":
# context.update({'another_variable': True})
return context
def done(self, form_list, form_dict, **kwargs):
# do something with the form data(form_list)
subcategory = form_dict['subcategory'].save()
print("============")
print(subcategory)
print("============")
address = form_dict['address'].save()
task = form_dict['task-details'].save()
return HttpResponseRedirect('/tasks')
def get_step_url(self, step):
return reverse(self.url_name, kwargs={'step':step})
// urls.py
from django.conf.urls import url
from .views import CreateTaskView, TaskDetailView
from . import views
from .forms import ChooseSubcategoryForm, SetAddressForm, AddTaskDetailsForm
app_name='tasks'
named_task_forms = (
("subcategory", ChooseSubcategoryForm),
("address", SetAddressForm),
("task-details", AddTaskDetailsForm),
)
task_wizard = views.AddTaskWizard.as_view(named_task_forms, url_name="task_step")
urlpatterns = [
url(r'^add_task/(?P<step>\w+)/$', task_wizard, name='task_step'),
]
// step1.html => subcategory form
<div class="row" id="create-task-progress">
<div class="container">
<div class="col-md-4 section-static border-top-gray text-center">
<span class="glyphicon glyphicon-search glyphicon-md orange" ></span> <span class="orange">1. Choose Subcategory</span>
</div>
<div class="col-md-4 section-static col-middle text-center">
<span class="glyphicon glyphicon-home glyphicon-md" ></span> <span>2. Set Address</span>
</div>
<div class="col-md-4 section-static border-top-gray text-center">
<span class="glyphicon glyphicon-pencil glyphicon-md"></span> <span>3. Task Details</span>
</div>
</div>
</div>
<div class="row section-light-gray border-top-gray">
<div class="container" id="task-form-container">
<div class="col-md-12">
<form action="{% url 'tasks:task_step' wizard.steps.current %}" method="POST" enctype="multipart/form-data" class="col-md-10 col-md-push-1">
{% csrf_token %}
{{ wizard.management_form }}
<div class="col-md-12 task-field-container">
{{ wizard.form.subcategory.label }}
{{ wizard.form.subcategory }}
</div>
<input type="submit" value="Continue" id="add_task" class="btn btn-primary col-xs-12" />
</form>
</div>
</div>
</div>
Based on what I see in your template, you're using url namespaces.
I believe you need to change
task_wizard = views.AddTaskWizard.as_view(named_task_forms, url_name="task_step")
to
task_wizard = views.AddTaskWizard.as_view(named_task_forms, url_name="tasks:task_step")
So you're just missing the tasks:

Categories