Flask get and edit values - python-3.x

I've got a site where I display specific values of a stock in a table and then should be able to change those values again when clicking on a button, that opens a modal with a form inside.
Now this is my first flask app and I’ve got a problem in overwriting my “original” data with the new Data I’m getting from my form. I don't really know how I can do that. My code looks like this:
views.py
#app.route("/stock-editor", methods=['GET', 'POST'])
def stock_editor():
index = Index(initial_date=app.config['INCEPTION_DATE'], initial_value=10000)
end_date = datetime.today()
start_date = app.config['INCEPTION_DATE']
empty_stocks = dict()
for symbol, shares in index.share_distribution.items(): # Here I get every empty stock and put inside a dict so that I can show it on my page
stock_value = StockValue.query.filter(StockValue.value_eur == 0.000000, StockValue.identifier == symbol, StockValue.date <= end_date, StockValue.date >= start_date).all()
if stock_value:
empty_stocks[symbol] = stock_value
if request.method == 'POST': # this is where I am failing, more info below
result = request.form
new_stock_value = request.values.get('new-stock-value')
new_source_value = request.values.get('new-source-value')
return render_template('stock-editor.html', result=result, empty_stocks=empty_stocks, start_date=start_date, end_date=end_date, new_stock_value=new_stock_value, new_source_value=new_source_value)
else:
return render_template('stock-editor.html', empty_stocks=empty_stocks, start_date=start_date, end_date=end_date)
The html:
<table class="table">
<tbody>
{% for symbol, stock_values in empty_stocks.items() %}
<tr class="table-active">
<th>Aktie</th>
<th>Datum</th>
<th>Wert</th>
<th colspan="2">Quelle</th>
</tr>
{% for value in stock_values %}
<tr>
<th>{{ symbol }}</th>
<td>{{ value.date.strftime('%d.%m.%Y')}}</td>
<td>{{ '%d' % value.value_eur }}</td>
<td>{{ value.source }}</td>
<td>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#modal-{{ value.id }}">Bearbeiten <i class="fas fa-pencil-alt"></i></button>
<!-- The Modal -->
<div class="modal fade" id="modal-{{ value.id }}">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Aktie bearbeiten</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<form method="POST">
<label for="new-stock-value" class="col-form-label">Neuer Wert:</label>
<input type="number" name="new-stock-value" class="form-control" id="new-stock-value" placeholder="{{ '%d' % value.value_eur }}">
<label for="new-source-value" class="col-form-label">Quelle:</label>
<input type="text" name="new-source-value" class="form-control" id="new-source-value" placeholder="{{ value.source }}">
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit" class="btn btn-success">Ändern</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Abbrechen</button>
</div>
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>
So in the if request.method == 'POST' I am getting my new values (new_stock_value and new_source_value) but I’m a little lost in HOW to actually set them as the new value of the stock where I am setting those new values?

Add a hidden field like below to the modal form,
<input type='hidden' name='id' value='{{ value.id }}'>
The above code snippet allows you to send the id of the current stock which is being edited. And in the route you can grab this id by,
id = request.values.get('id')
Using this id, update the empty_stocks dictionary with the new value of stock.
for symbol, stock_values in empty_stocks:
for value in stock_values:
if value.id == id:
value.value_eur = request.values.get('new-stock-value')
value.source = request.values.get('new-source-value')
break
I hope this helped you.

Related

Template not rendering Django (NoReverseMatch)

I am not exactly sure what the issue is but I have this code in my project that once I select a date it will bring up a table with the name of students in my classroom but Django keeps telling me that there isnt NoReverseMatch. i have double check and everything is fine but not sure why it not working.
ERROR SHOWN
Reverse for 'attendance-page' with arguments '('',)' not found. 1 pattern(s) tried: ['attendance/(?P[0-9]+)\Z']
urls.py
path('attendance_class', views.attendance_class, name='attendance-class'),
path('attendance/<int:classPK>', views.attendance, name='attendance-page'),
path(r'attendance/<int:classPK>/<str:date>',views.attendance, name='attendance-page-date'),
path('save_attendance', views.save_attendance, name='save-attendance'),
views.py
#login_required
def attendance_class(request):
classes = Room.objects.all()
context = {}
context['classes'] = classes
return render(request, 'school/attendance_page.html', context)
#login_required
def attendance(request, classPK=None, date=None):
_class = Room.objects.get(id=classPK)
students = Student.objects.filter(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student')).all()
context = {}
context['class'] = _class
context['date'] = date
att_data = {}
for student in students:
att_data[student.id] = {}
att_data[student.id]['data'] = student
if not date is None:
date = datetime.strptime(date, '%Y-%m-%d')
year = date.strftime('%Y')
month = date.strftime('%m')
day = date.strftime('%d')
attendance = Attendance.objects.filter(
attendance_date__year=year, attendance_date__month=month, attendance_date__day=day, classIns=_class).all()
for att in attendance:
att_data[att.student.pk]['type'] = att.type
print(list(att_data.values()))
context['att_data'] = list(att_data.values())
context['students'] = students
return render(request, 'school/attendance_control.html')
def save_attendance(request):
resp = {'status': 'failed', 'msg': ''}
if request.method == 'POST':
post = request.POST
date = datetime.strptime(post['attendance_date'], '%Y-%m-%d')
year = date.strftime('%Y')
month = date.strftime('%m')
day = date.strftime('%d')
_class = Room.objects.get(id=post['classIns'])
Attendance.objects.filter(attendance_date__year=year, attendance_date__month=month,
attendance_date__day=day, classIns=_class).delete()
for student in post.getlist('student[]'):
type = post['type['+student+']']
studInstance = Student.objects.get(id=student)
att = Attendance(student=studInstance, type=type, classIns=_class,
attendance_date=post['attendance_date']).save()
resp['status'] = 'success'
messages.success(request, "Attendance has been saved successfully.")
return HttpResponse(json.dumps(resp), content_type="application/json")
Jquery used
<script>
$(document).ready(function () {
$('table td, table th').addClass('px-2 py-1')
$('#data-form').change(function() {
location.href = "{% url 'attendance-page' class.pk %}/" + $(this).val()
})
$('#attendance-form').submit(function (e) {
e.preventDefault()
var _this = $(this)
$('.err-msg').remove();
var el = $('<div>')
el.addClass("alert alert-danger err-msg")
el.hide()
start_loader()
$.ajax({
url: "{% url 'save-attendance' %}",
data: $(this).serialize(),
method: 'POST',
type: 'POST',
dataType: 'json',
error: err => {
console.log(err)
alert("An error occured ", 'error');
end_loader();
},
success: function (resp) {
if (typeof resp == 'object' && resp.status == 'success') {
el.removeClass("alert alert-danger err-msg ")
location.reload()
} else if (resp.status == 'failed' && !!resp.msg) {
el.html(resp.msg)
} else {
el.text("An error occured ", 'error');
end_loader();
console.err(resp)
}
_this.prepend(el)
el.show('slow')
$("html, body, .modal ").scrollTop(0);
end_loader()
}
})
})
})
</script>
attendance template
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card card-default rounded-0 shadow ">
<div class="card-header">
<div class="d-flex w-100 align-items-center justify-content-between">
<h4 class="card-title fw-bold">Class Attendance Management</h4>
<div class="tools">
</div>
</div>
</div>
<div class="card-body">
<form id="attendance-form">
{% csrf_token %}
<input type="hidden" name="classIns" value="{{ class.pk }}">
<div class="container-fluid">
<fieldset>
<legend>Class Details</legend>
<div class="row">
<!-- <div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Department:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.assigned_faculty.department }}</p>
</div>
</div>
</div> -->
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">School Year:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.school_year }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Level:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.level }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Name:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.name }}</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="d-flex w-100">
<div class="col-auto pe-2 text-muted">Faculty:</div>
<div class="col-auto flex-shrink-1 flex-grow-1">
<p class="m-0 fw-bold">{{ class.form_teacher}}</p>
</div>
</div>
</div>
</div>
</fieldset>
<hr>
<fieldset>
<legend>Date of Class</legend>
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12">
<input id="data-form" type="date" name="attendance_date" value="{% if date %}{{ date }}{% endif %}"class="form-control form-control-lg rounded-0" required>
</div>
</div>
</fieldset>
{% if date %}
<fieldset>
<legend>Attendance List</legend>
<table class="table tables-bordered" id="student-list">
<colgroup>
<col width="5%">
<col width="25%">
<col width="25%">
<col width="15%">
<col width="15%">
<col width="15%">
</colgroup>
<thead>
<tr>
<th class="text-ceter">#</th>
<th class="text-ceter">Student Code</th>
<th class="text-ceter">Student Name</th>
<th class="text-ceter">Total Tardy</th>
<th class="text-ceter">Total Absent</th>
<th class="text-ceter">Total Present</th>
</tr>
</thead>
<tbody>
{% for student in att_data %}
<tr class="">
<td class="text-center">{{ forloop.counter }}</td>
<td>{{ student.data.student_code }}</td>
<td>{{ student.data.first_name }} {{ student.data.middle_name }} {{ student.data.last_name }}</td>
<td class="text-center">
<input type="hidden" name="student[]" value="{{ student.data.pk }}">
<input type="radio" class="btn-check" name="type[{{ student.data.pk }}]" value="1"
id="btnradio-{{student.data.pk}}" {% if student.type == '1' %} checked="checked" {% endif %}
autocomplete="off" required>
<label class="btn btn-outline-primary btn-sm px-1 py-0" for="btnradio-{{student.data.pk}}"><i
class="fa fa-check text-light"></i></label>
</td>
<td class="text-center">
<input type="radio" class="btn-check" name="type[{{ student.data.pk }}]" value="2"
id="btnradio-2-{{ student.data.pk }}" {% if student.type == '2' %} checked="checked" {% endif %}
autocomplete="off">
<label class="btn btn-outline-warning btn-sm px-1 py-0" for="btnradio-2-{{ student.data.pk }}"><i
class="fa fa-check text-light"></label>
</td>
<td class="text-center">
<input type="radio" class="btn-check" name="type[{{ student.data.pk }}]" value="3"
id="btnradio-3-{{ student.data.pk }}" {% if student.type == '3' %} checked="checked" {% endif %}
autocomplete="off">
<label class="btn btn-outline-danger btn-sm px-1 py-0" for="btnradio-3-{{ student.data.pk }}"><i
class="fa fa-check text-light"></label>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="clear-fix py-3"></div>
<center>
<button class="btn btn-sm btn-primary rounded-0 bg-gradient"><i class="fa fa-save"></i>
Save</button>
</center>
</fieldset>
{% endif %}
</div>
</form>
</div>
</div>
</div>
It's this line location.href = "{% url 'attendance-page' class.pk %}/" + $(this).val()
class.pk is not defined so it tries to call url with 0 arguments while it needs only one.

Django view function isnt working correctly

so the basic goal of my project is to allow teachers and admin to login to the system and take attendance for the students. my new issue is that i have a view function that is suppose to check to see if students student is already added to the respective class and if they are it will exclude them from the drop down menu and display the students who aren't in the class but it not doing that instead it is showing me a blank drop down menu. the way i have it set up is that the admin clicks the add student button then it will convert a .html page to modal which brings up the list of students to select from. When i add the form responsible for saving the student to the class in the Django admin it work perfect but i cant seem to get it to work in the user section Ui. I am new to Django and this is my first project so any help is really appreciated
Views
#check to see if students already exist in class and display those who aint to be added
#login_required
def manage_class_student(request, classPK=None):
if classPK is None:
messages.warning(request,'Class ID is Unknown')
else:
context['classPK'] = classPK
_class = Room.objects.get(id=classPK)
# print(ClassStudent.objects.filter(classIns = _class))
students = Student.objects.exclude(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student').distinct()).all()
context['students'] = students
return render(request, 'manage_class_student.html', context)
#save the students to the respective class after being selected
#login_required
def save_class_student(request):
form = SaveClassStudent()
if request.method == 'POST':
form = SaveClassStudent(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Student has been added successfully.")
redirect('class_detail')
else:
messages.error(request, 'Error Adding student in class')
template with the form to show the available students
<!-- Modal -->
<div class="modal fade" {% block modal-id %} id="addModal{{class.pk}}" {% endblock%} data-bs-backdrop="static"
data-bs-keyboard="false" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="addModalLabel"> {% block modal-title%}<i class="fas fa-plus"></i> Add
Student To Class{% endblock%}</h6>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="container-fluid">
<form {% block action %} action="{% url 'save-class-student' %}" {% endblock%} method="post">
{% csrf_token %}
<div class="modal-body">
<input type="hidden" name="classIns" value="{{ classPK }}">
<div class="form-group mb-3">
<label for="student" class="control-label">Student</label>
<select name="student" id="student" class="form-select rounded-0 select2" required>
<option disabled selected></option>
{% for student in students %}
<option value="{{ student.id }}">{{ student }}</option>
{% endfor %}
</select>
</div>
<div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
What triggers the modal
<div class="tools">
<button type="button" class="btn btn-secondary border rounded-0 bg-gradient btn-sm"
id='print_attendance_report'><i class="fa fa-print"></i> Print Attendance Report</button>
<a data-bs-toggle="modal" data-bs-target="#addModal{{class.pk}}"> <button type="button"
class="btn btn-primary rounded-0 bg-gradient btn-sm" id='add_new'><i class="fa fa-plus"></i>
Add Student</button></a>
</div>
form that save students to classroom
class SaveClassStudent(forms.ModelForm):
classIns = forms.IntegerField()
student = forms.IntegerField()
class Meta:
model = ClassStudent
fields = ('classIns', 'student')
def clean_classIns(self):
cid = self.cleaned_data['classIns']
try:
classIns = Room.objects.get(id=cid)
return classIns
except:
raise forms.ValidationError("Class ID is Invalid.")
def clean_student(self):
student_id = self.cleaned_data['student']
_class = Room.objects.get(id=self.data.get('classIns'))
student = Student.objects.get(id=student_id)
try:
cs = ClassStudent.objects.get(classIns=_class, student=student)
if len(cs) > 0:
raise forms.ValidationError(
f"Student already exists in the Class List.")
except:
return student

How to fetch data from database and show it in bootstrap's modal box ( pop up ) in django respectively?

Technologies I'm using --> Back-end --> Python, Web Framework --> Django, Front-end --> HTML5, CSS3, Bootstrap 4, Database --> SQLite3.
What I want --> To display the data of each object in each bootstrap's modal box( popup ).
The problem --> Data of the first object is only being shown in all the modal boxes( popups ).
Files are as follows:
HTML template --> manage_requisition.html 👇
{% extends 'hod_template/base_template.html' %}
{% block page_title %}
Manage Requisitions
{% endblock page_title %}
{% block main_content %}
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">Manage Requisitions</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<div class="table">
<table class="table">
<tr>
<th style="text-align: center;">Action</th>
<th>View Requisition</th>
</tr>
{% for requisition in requisitions %}
<tr>
<td style="text-align: center; vertical-align: middle;">
{% if requisition.requisition_status == 0 %}
<a style="width: 85px;" href="{% url 'supervisor_approve_requisition' requisition_id=requisition.id %}" class="btn btn-success inline" >Approve</a>
<a style="width: 85px;" class="btn btn-danger inline" href="{% url 'supervisor_rejected_requisition' requisition_id=requisition.id %}" >Reject</a>
{% elif requisition.requisition_status == 1 %}
<button class="btn btn-warning" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Approved</button>
{% else %}
<button class="btn btn-danger" disabled="disabled" data-toggle="modal" data-target="#reply_modal">Rejected</button>
{% endif %}
</td>
<td>
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#reqModal">
View Requisition
</button>
<div class="modal" id="reqModal" tabindex="-1" aria-labelledby="reqModal" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="reqModalTitle">Requisition Details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p><strong>Position Required :</strong> {{ requisition.position_required }}</p>
<p><strong>Requirement :</strong> {{ requisition.requirement }}</p>
<p><strong>Candidate Name :</strong> {{ requisition.candidate_name }}</p>
<p><strong>Department :</strong> {{ requisition.department }}</p>
<p><strong>Post :</strong> {{ requisition.post }}</p>
<p><strong>Requirement Time Period :</strong> {{ requisition.requirement_time_period }}</p>
<p><strong>Work Type :</strong> {{ requisition.work_type }}</p>
<p><strong>Duration Start Date :</strong> {{ requisition.duration_start_date }}</p>
<p><strong>Duration End Date :</strong> {{ requisition.duration_end_date }}</p>
<p><strong>Requisition Reason :</strong> {{ requisition.requisition_reason }}</p>
<p><strong>Minimum Qualification :</strong> {{ requisition.min_qualification }}</p>
<p><strong>Maximum Qualification :</strong> {{ requisition.max_qualification }}</p>
<p><strong>Minimum Experience :</strong> {{ requisition.min_experience }}</p>
<p><strong>Maximum Experience :</strong> {{ requisition.max_experience }}</p>
</div>
<div class="modal-footer">
</div>
</div>
</td>
</tr>
{% endfor %}
</table>
</div>
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<!-- Modal -->
<!-- /.content -->
{% endblock main_content %}
Views file --> HODviews.py 👇
def Manage_Requisitions(request):
requisitions = Requisition.objects.all()
context = {"requisitions":requisitions}
return render(request, "hod_template/manage_requisition.html", context)
urls.py file --> urls.py 👇
path("manage_requisition/", HODviews.Manage_Requisitions, name="manage_requisition")
models.py file --> models.py 👇
class Requisition(models.Model):
id = models.AutoField(primary_key=True)
position_required = models.CharField(max_length=2000, default="")
requirement_choices = (
("New", "New"),
("BackFill", "BackFill")
)
requirement = models.CharField(max_length=100, choices=requirement_choices, default="")
candidate_name = models.CharField(max_length=2000, default="")
department = models.CharField(max_length=2000, default="")
post = models.CharField(max_length=2000, default="")
requirement_type = (
("Permanent", "Permanent"),
("Temporary", "Temporary"),
("Fixed Contract", "Fixed Contract")
)
requirement_time_period = models.CharField(max_length=500, choices=requirement_type, default="")
work_type = (
("Full-Time", "Full-Time"),
("Part-Time", "Part-Time")
)
work_type = models.CharField(max_length=500, choices=work_type, default="")
duration_start_date = models.DateField(blank=True)
duration_end_date = models.DateField(blank=True)
requisition_reason = models.TextField()
min_qualification = models.CharField(max_length=1000 ,default="")
max_qualification = models.CharField(max_length=1000 ,default="")
min_experience= models.CharField(max_length=1000 ,default="")
max_experience= models.CharField(max_length=1000 ,default="")
requisition_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.candidate_name
Image of the UI 👇
Image of the first pop up 👇
Image of the second popup 👇
I'm getting the data of first objet in each popup. But I want the data of every object to be displayed in each popup.
You can contact me here 👇
Linkedin --> https://www.linkedin.com/in/precioushuzaifa/
Instagram --> https://www.instagram.com/precious_huzaifa/
The problem is all your modals have the same id and so your buttons are just going to open the first modal they find with the ID. You need to add some sort of id to each modal. you can use {{ forloop.counter }} to get the iteration number and attach that to the id.
<button type="button" class="btn btn-warning" data-toggle="modal" data-target="#reqModal-{{ forloop.counter }}">
View Requisition
</button>
<div class="modal" id="reqModal-{{ forloop.counter }}" tabindex="-1" aria-labelledby="reqModal" aria-hidden="true">

Edit and Update Method is Not working

My problem is, edit and update the values by using python-flask from client side. I don't have any idea about that and new python-flask using MySQL database. I tried this method for edit and update purpose.But, it's not working.Additionally the details will be added in database when we enter details and submit. anyone help me.
Here is vehicletype.html template.
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype > Create Vehicletype</li>
</ol>
</div>
<div class="row">
<div class="col-md-6">
<form role="form" action="/post/vehicletype" method="post">
<div class="form-group">
<label>VehicleType: </label>
<input name="type" class="form-control" placeholder="enter vehicletype">
</div>
<input type="submit" class="btn btn-primary" value="Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
{% endblock %}
Here is the details.html
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype>View</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
Id
</th>
<th>
VehicleType
</th>
<th>
Dateofsub
</th>
<!--<th>
Control
</th>-->
<th>
Delete
</th>
</tr>
</thead>
{% for values in vehicletype %}
<tr>
<th>{{values.id}}</th>
<td>{{values.type}}</td>
<td>{{values.dateofsub}}</td>
<!--<td>Reset Password</td>-->
<td>Delete</td>
<td>edit</td>
</tr>
{% endfor %}
</table>
<em class="fa fa-xl fa-plus-circle color-blue" ></em>
</div>
</div>
{% endblock %}
python code for Edit method:
class VehicetypeForm(FlaskForm):
type=StringField('Type')
#app.route('/control/edit/<int:id>',methods=['POST','GET','PATCH'])
def edit(id):
form = VehicetypeForm(request.form)
mysql = pymysql.connect("0.0.0.0", "tnxt", "tnxt", "transport")
cur = mysql .cursor()
cur.execute('SELECT * FROM vehicletype WHERE id= %s',[id])
type=cur.fetchall()
# form.type.data=type
if request.method=='PATCH' and form.validate():
#type=form.type.data
mysql = pymysql.connect("0.0.0.0", "tnxt", "tnxt", "transport")
cur=pymysql .cursor()
cur.execute('UPDATE vehicletype SET type=%s WHERE id=%s',(type,id))
mysql.connection.commit()
cur.close()
flash('success')
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html',form=form)
In this python code update method is not working. But, when we give the details that details will be added in database. How to edit and update the values from client side.
Below is the good practice to create form using wtforms
class UserForm(Form):
name = StringField('Name')
father_name = StringField('Father Name')
# .... add fields you want
for field types - refer to this link
#app.route('/newuser', methods=['GET', 'POST'])
def add_user():
form = UserForm()
if form.validate_on_submit():
user_details = {
name: form.name.data,
fathername: form.father_name.data,
# add more fields
}
sqlsession.add(user_details)
return redirect(url_for('page_newuser'))
return render_template('newuser.html', form=form)
Once you have form then you can easily edit your content and directly save it to database
#app.route('/control/edituser/<int:id>',method=['post','get'])
def edit(id):
qry=sqlsession.query(Enduser).filter(Enduser.id==id).first()
form = UserForm(request.form, **qry)
if form.validate_on_submit():
form.populate_obj(qry)
sqlsession.update(qry)
sqlsession.commit()
return redirect(url_for('page_newuser'))
return render_template('newuser.html', form=form)

Passing data from django form to ListView

Above is an image of what I am attempting to build: A form that is at the top while the area to display a result list is below. When I hit 'Go!', the part below does not render the list as I hoped. Also, I am not sure if this is the 'proper' way to go about doing this.
The Class Based View that i use:
class EntryListView(ListView):
template_name = 'finance/entry_list.html'
now = datetime.now()
year = now.year
context_object_name = 'entry_list'
model = Entry
paginate_by = 10
month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December']
year_list = list(range(Entry.objects.earliest('input_date').input_date.year,
Entry.objects.latest('input_date').input_date.year))
def get_context_data(self, **kwargs):
context = super(EntryListView, self).get_context_data(**kwargs)
# https://stackoverflow.com/questions/18232851/django-passing-variables-to-templates-from-class-based-views
context.update({
'month_list': self.month_list,
'year_list': self.year_list,
})
return context
# This method ensures that I can customize the list of entries returned.
def get_queryset(self):
# https://stackoverflow.com/questions/22902457/django-listview-customising-queryset
if self.request.method == 'GET':
print('I have entered here!')
month = self.request.GET.get('month')
year = self.request.GET.get('year')
print('month: ' + str(month))
print('year: ' + str(year))
if month or year is None:
return Entry.objects.filter(input_date__month=datetime.now().month,
input_date__year=datetime.now().year).order_by('-input_date').all()
else:
return Entry.objects.filter(input_date__month=month,
input_date__year=year).order_by('-input_date').all()
Here is my urls.py:
url(r'entry/$', login_required(views.EntryListView.as_view()), name='list_entries'),
The EntryListView is also in charged of ensuring that the form is populated with the right 'Dropdown values'.
And here is the template:
{% extends 'base.html' %}
{% block body_content %}
<div class="wrapper">
{% include 'finance/finance_sidebar.html' %} <!-- Add this for inheritance -->
<div class="container">
<div class="row">
<form class="well contact-form" method='GET'>
<label>Month:</label>
<select class="well form-control" name="month">
{% for month in month_list %}
<option value="{{ forloop.counter }}">{{ month }}</option>
{% endfor %}
</select>
<label>Year:</label>
<select class="well form-control" name="year">
{% for year in year_list %}
<option value="{{ year }}">{{ year }}</option>
{% endfor %}
</select>
<button type="submit" class="btn btn-default">Go!</button>
</form>
</div>
<div class="row">
{% if entry_list %}
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>No.</th>
<th width="100">Input Date</th>
<th>Category</th>
<th>Tag</th>
<th>Description</th>
<th>Value</th>
<th>Transfer Type</th>
<th>Remarks</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for entry in entry_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ entry.input_date|date:'d M Y' }}</td>
<td>{{ entry.category }}</td>
<td>{{ entry.tag }}</td>
<td>{{ entry.description }}</td>
<td>${{ entry.value }}</td>
<td>{{ entry.transfer_type }}</td>
<td>{{ entry.remarks }}</td>
<td>
<form class="flex-container" method="post" action="{% url 'finance:update_entry' pk=entry.id %}" >
{% csrf_token %}
<div class="input-group">
<input type="hidden" name="id" value="{{ entry.id }}">
<button name="update" type="submit" class="btn btn-warning">EDIT </button>
</div>
</form>
</td>
<td>
<form class="flex-container" method="post" action="{% url 'finance:delete_entry' %}" >
{% csrf_token %}
<div class="input-group">
<input type="hidden" name="id" value="{{ entry.id }}">
<button name="delete" type="submit" class="btn btn-danger">DELETE </button>
</div>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="col-sm-7 col-sm-offset-5">
{% if is_paginated %}
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_page }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
{% endif %}
</div>
{% else %}
<p>Please make sure you have specified a month and the year.</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
I am again, not sure if this is the right way to approach it. I have seen something called Mixins, but I have no clue how to use them. I did a little print statements while debugging and i found that the data from the forms indeed are able to be accessed inside the get_queryset() method. I also made sure that my DB had such a record and i even typed it in my python shell to be sure that the query is not faulty.
Your if-else statement in your view is wrong. if month or year is None: will always evaluate to true since it can be rewritten as if (month) or (year is None) and you are actually posting month value to your view.
Instead, you could rewrite it as: if month is None or year is None:.

Resources