Edit and Update Method is Not working - python-3.x

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)

Related

In Django website even if I add an item by pressing add to cart button the status of True for the product added is not shown and still false is visibl

I have made a django e-comm website , when I press the add to cart button on my home page I have written a function which should change the status of a product from false to true once it is added in the cart but it does not work
I have given my cart.py and index.html code
Thank you
cart.py
from django import template
register = template.Library()
#register.filter(name='is_in_cart')
def is_in_cart(product,cart):
keys = cart.keys()
for id in keys:
print(id , product.id)
if int(id) == product.id:
return True
return False
index.html
{% extends 'main/base.html'%}
{% block title %}
index
{% endblock %}
{% block content %}
{% load cart %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-3">
<div class="list-group mt-3">
{% for items in category %}
{{items.Category_name}} <!--i first used a small c for category but it did not pick the words from my category.py fle-->
{% endfor %}
</div>
</div>
<div class="col-lg-9">
<div class="row">
{% for items in product %}
<div class="card mx-auto mb-3 mt-3" style="width: 18rem;">
<img class="card-img-top" src="{{items.product_image.url}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{items.product_name}}</h5>
<p class="card-text"><b>{{items.product_price}}</b></p>
<p class="card-text"><b>{{items.product_detail}}</b></p>
{{product | is_in_cart:request.session.cart }}
<form action="/" mthod="POST">
{% csrf_token %}
<input hidden type="text" name='product' value='{{items.id}}'>
<input href="#" type="submit" class="float-right btn btn-light border btn-sm" value="Add to Cart">
</form>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock %}

Django models choice textField mapping

I am building a website for myself I am updating my projects from django admin I wanted to create a custom field which is a map of choice(tag color) and tag text.
I want to make it look something like this
This is my model
class Project(models.Model):
projectTemplate = CloudinaryField('image')
projectTitle = models.TextField(default="Title ")
desc = models.TextField(default="not mentioned")
projectLink = models.URLField(max_length=200, default="not mentioned")
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.projectTitle} - {self.desc[:15]} ..'
views.py
def projects(request):
Projects = Project.objects.all()
return render(request, 'devpage/projects.html',{'Projects': Projects})
This is my current DTL
{% for project in Projects %}
<div class="col">
<div class="card shadow-sm">
<img src="{{ project.projectTemplate.url }}" height="225" width="100%">
<div class="card-body">
<h6 class="text-center">
{{ project.projectTitle }}
</h6>
<p class="card-text">{{ project.desc }}</p>
<div class="mb-3">
<span class="badge rounded-pill bg-secondary">Django</span>
<span class="badge rounded-pill bg-success">Python</span>
</div>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-warning btn-outline-secondary"><a
href="{{ project.projectLink }}" target="_blank" type="button"
class="btn">View</a></button>
</div>
<small class="text-muted">{{ project.created_at }}</small>
</div>
</div>
</div>
</div>
{% endfor %}
I want a custom model field which takes choice of label color and corresponding text with dynamic size I tried using json(field name tags) but its not interactive its like {"primary":"django","success":"Python","seconday":"webApp"}
This is JSON DTL
//Inner for loop for tags
<div class="mb-3">
{% for color,text in Project.tags.items %}
<span class="badge rounded-pill bg-{{ color }}">{{ text }}</span>
{% endfor %}
</div>
Assuming you have a Tag model which is a ManyToManyField, you could just store the color as an attribute to the model.
Your model:
class Tag(models.Model):
text = models.CharField(max_length=32)
color = models.CharField(max_length=32, default="bg-success")
class Project(models.Model):
...
tags = models.ManyToManyField(Tag)
Your template:
{% for tag in Project.tags %}
<span class="badge rounded-pill {{ tag.color }}">{{ tag.text }}</span>
{% endfor %}
Some future improvement to this could be a subclass that pre-defines all of the colors.

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

How add space between two cards - bootstrap?

I was creating a simple blog page using Django. When I added cards for the articles it came like this
There is no space between the cards.
{% extends 'base.html' %}
{% block content %}
<div class="card mt-3" style="width: 100%;">
{% for post in posts %}
<div class="card-header">
<cite title="Source Title">{{ post.author }}</cite>
<small class="text-muted float-right">{{ post.date_posted | date:"F d, Y" }}</small>
</div>
<div class="card-body">
<div class="card-title">{{ post.title }}</div>
<p class="card-text">{{ post.content }}</p>
</div>
{% endfor %}
</div>
{% endblock content %}
How do I add space between these cards?
your for loop is not in correct place change code from
{% extends 'base.html' %}
{% block content %}
<div class="card mt-3" style="width: 100%;">
{% for post in posts %}
<div class="card-header">
<cite title="Source Title">{{ post.author }}</cite>
<small class="text-muted float-right">{{ post.date_posted | date:"F d, Y" }}</small>
</div>
<div class="card-body">
<div class="card-title">{{ post.title }}</div>
<p class="card-text">{{ post.content }}</p>
</div>
{% endfor %}
</div>
{% endblock content %}
to bellow code
{% extends 'base.html' %}
{% block content %}
{% for post in posts %}
<div class="card mt-3" style="width: 100%;">
<div class="card-header">
<cite title="Source Title">{{ post.author }}</cite>
<small class="text-muted float-right">{{ post.date_posted | date:"F d, Y" }}</small>
</div>
<div class="card-body">
<div class="card-title">{{ post.title }}</div>
<p class="card-text">{{ post.content }}</p>
</div>
</div>
{% endfor %}
{% endblock content %}
Firstly, you need to do the loop for every card, instead of doing it for the inner divs 'card-header' and 'card-body'. Secondly, to answer you question, you should use a spacing by either a margin or a padding.
I would suggest to make the cards a standard width and use a 'margin right 3':
{% for post in posts %}
<div class="card mt-3 mr-3" style="width: 250px">
<div class="card-header">
...
</div>
<div class="card-body">
...
</div>
</div>
{% endfor %}
Besides this solution, I suggest you read the Bootstaps Grid Layout documentation, so you can place the cards nicely within your content block.

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