Staying on same page after updating search data in flask - python

I need to stay on the search result after updating row. Currently, I am using update.html to post data to #update after that render update.html and call update modal of bootstrap to get data from particular row. After that call update_two to update row in mysql using SqlAlchemy. Then trying to stay at the search result.
app.py
#app.route('/update', methods=['GET', 'POST'])
def update():
# all_data = BankData.query.all()
if request.method == 'POST':
start_date = request.form.get('start_date')
end_date = request.form.get('end_date')
searched_data = db.session.query(BankData).filter(
BankData.process_date.between(start_date, end_date))
# db.session.add(searched_data)
# db.session.commit()
return render_template('update.html', start_date=start_date, end_date=end_date, searched_data=searched_data)
#app.route('/update_two', methods=['GET', 'POST'])
def update_two():
# searched_data = session.get('searched_data')
if request.method == 'POST':
new_data = BankData.query.get(request.form.get('true_id'))
new_data.process_date = request.form['date']
new_data.description = request.form['description']
new_data.debit = request.form['debit']
new_data.category = request.form['category']
db.session.commit()
return redirect(request.url)
update.html
{% extends 'base.html' %}
{% include 'header.html' %}
{%block title%} Home {%endblock%}
{%block body%}
<div class="container">
<div class="row">
<div class="col md-12">
<div class="jumbotron p-3">
<h2>Bank Transaction date from <b
style="margin: 15px; background-color: dimgrey;">{{start_date}}</b>-To-<b
style="margin: 15px; background-color: dimgrey;">{{end_date}}</b></h2>
</div>
<table class="table table-hover table-dark">
<tr>
<th>Date</th>
<th>Description</th>
<th>Debit</th>
<th>Category</th>
<!-- <th>Category</th> -->
</tr>
{% for data in searched_data %}
<tr>
<!-- <td>{{data.id}}</td> -->
<td>{{data.process_date}}</td>
<td>{{data.description}}</td>
<td>{{data.debit}}</td>
<td>{{data.category}}</td>
<td>
<a href="/update/{{data.id}}" class="btn btn-warning btn-xs" data-toggle="modal"
data-target="#modaledit{{data.id}}">Edit</a>
<!-- <a href="/delete/{{data.id}}" class="btn btn-danger btn-xs"
onclick="return confirm('Are You Sure To Delete ?')">Delete</a> -->
</td>
</tr>
<!-- Modal Edit Employee-->
<div id="modaledit{{data.id}}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Update Information</h4>
</div>
<div class="modal-body">
<form action="{{url_for('update_two')}}" method="POST">
<div class="form-group">
<label>Date</label>
<input type="hidden" name="true_id" value="{{data.id}}">
<input type="text" class="form-control" name="date"
value="{{data.process_date}}">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" class="form-control" name="description"
value="{{data.description}}">
</div>
<div class="form-group">
<label>Debit:</label>
<input type="text" class="form-control" name="debit" value="{{data.debit}}">
</div>
<div class="form-group">
<label>Category:</label>
<select id="category" name="category">
<option selected value="None">{{data.category}}</option>
<option value="BankFees">Bank Fees</option>
<option value="StaffExpences">Staff Expence</option>
<option value="Refund">Refund</option>
<option value="Telephone">Telephone</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Update</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{% endfor %}
</table>
</div>
</div>
</div>
</div>
{%endblock%}

If I'm correct:
With /update endpoint you render search results from the database, and then with /update_two endpoint, you update the database with new data or so...
And then you would like that after /update_two finishes it's job to see previous or new search results (that was done with /update endpoint), so you could change what you return in /update_two, so it would redirect to 1st endpoint /update like this:
from flask import url_for
#app.route('/update_two', methods=['GET', 'POST'])
def update_two():
# searched_data = session.get('searched_data')
if request.method == 'POST':
new_data = BankData.query.get(request.form.get('true_id'))
new_data.process_date = request.form['date']
new_data.description = request.form['description']
new_data.debit = request.form['debit']
new_data.category = request.form['category']
db.session.commit()
return redirect(url_for('update'))

Related

I am not able to perform update operation in crud

I am trying to perform update operation in Django. Actually what I need when I click the update button of an existing entry it should load in an another form with the data and once I change the details need to save it. I have referred a video with same requirement but that code is not working for me. Please help me I am really stuck.
These are my files and code details.
forms.py
from .models import Building
from django.forms import ModelForm
class BuildingForm(ModelForm):
class Meta:
model = Building
fields = '__all__'
models.py
from django.db import models
# Create your models here.
class BuildingType(models.Model):
building_type = models.CharField(max_length=100)
def __str__(self):
return self.building_type
class Building(models.Model):
building_name = models.CharField(max_length=50)
name_of_owner = models.CharField(max_length=50)
building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE)
number_of_rooms = models.IntegerField()
mobile_number = models.IntegerField()
current_lease_period = models.DateField()
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='home'),
path('buildings', views.Buildings, name='buildings'),
path('rooms', views.Rooms, name='rooms'),
path('customers', views.Customers, name='customers'),
path('receipts', views.Receipts, name='receipts'),
path('new_building', views.NewBuilding, name='new_building'),
path('update/<int:bldg_id>', views.UpdateBuilding, name='update_building'),
path('delete_building/<int:bldg_id>', views.DeleteBuilding, name='delete_building'),
path('new_room', views.NewRoom, name='new_room'),
path('new_customer', views.NewCustomer, name='new_customer'),
path('new_receipt', views.NewReceipt, name='new_receipt'),
path('login', views.Login, name='login'),
path('signup', views.Signup, name='signup'),
]
views.py
from django.shortcuts import render, redirect
from .forms import BuildingForm
from webapp.models import Building, BuildingType
# Create your views here.
def Home(request):
return render(request, 'index.html', {'context':'null'})
def Buildings(request):
building_list = Building.objects.all()
return render(request, 'buildings.html', {'context': 'Buildings', 'building_list': building_list})
def Rooms(request):
return render(request, 'rooms.html', {'context':'Rooms'})
def Customers(request):
return render(request, 'customers.html', {'context':'Customers'})
def Receipts(request):
return render(request, 'receipts.html', {'context':'Receipts'})
# New Building
def NewBuilding(request):
bldg_type = BuildingType.objects.all()
form = BuildingForm()
if request.method == "POST":
form = BuildingForm(request.POST)
if form.is_valid():
form.save()
return redirect('buildings')
else:
form = BuildingForm()
return render(request, 'new_building.html', {'context':'NewBuilding', 'bldg_type':bldg_type, 'form':form})
**
# Update Building
def UpdateBuilding(request, bldg_id):
bldg_type = BuildingType.objects.all()
Update_building = Building.objects.get(id=bldg_id)
form = BuildingForm(instance=Update_building)
return render(request, 'update_building.html', {'context':'UpdateBuilding', 'bldg_type':bldg_type, 'form':form})**
# Delete Building
def DeleteBuilding(request, bldg_id):
building_list = Building.objects.all()
if request.method == "POST":
bldg=Building.objects.get(id=bldg_id)
bldg.delete()
return redirect('buildings')
return render(request, 'buildings.html', {'building_list':building_list})
def NewRoom(request):
return render(request, 'new_room.html', {'context':'NewRoom'})
def NewCustomer(request):
return render(request, 'new_customer.html', {'context':'NewCustomer'})
def NewReceipt(request):
return render(request, 'new_receipt.html', {'context':'NewReceipt'})
def Login(request):
return render(request, 'login.html')
def Signup(request):
return render(request, 'signup.html')
buildings.html
{% extends 'base.html' %}
{% load static %}
{% block title %} Buildings {% endblock %}
{% block content %}
<!-- Buildings -->
<div class="container-fluid">
<div class="sub-box">
<div class="row">
<div class="col-sm-12 mt-3">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 search-col">
<form action="" class="d-flex gap-3">
<input type="text" class="form-control form-control-lg" id="search" >
<button type="submit" class="btn btn-lg search">Search</button>
</form>
</div>
</div>
</div>
<div class="col-sm-12 mt-3 table-responsive">
<table class="table table-hover table-bordered text-center ">
<thead>
<tr>
<th scope="col" class="align-middle">Building Name</th>
<th scope="col" class="align-middle">Building Type</th>
<th scope="col" class="align-middle">Rooms</th>
<th scope="col" class="align-middle">Owner Name</th>
<th scope="col" class="align-middle">Mobile Number</th>
<th scope="col" class="align-middle">Lease Period</th>
<th scope="col" class="align-middle">Actions</th>
</tr>
</thead>
<tbody>
{% for list in building_list %}
<tr>
<td class="align-middle">{{list.building_name}}</td>
<td class="align-middle">{{list.building_type}}</td>
<td class="align-middle">{{list.number_of_rooms}}</td>
<td class="align-middle">{{list.name_of_owner}}</td>
<td class="align-middle">{{list.mobile_number}}</td>
<td class="align-middle">{{list.current_lease_period}}</td>
<td class="d-flex justify-content-between gap-3">
Update
<form action="{% url 'delete_building' list.id %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete" class="btn delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
update_building.html
{% extends 'base.html' %}
{% load static %}
{% block title %} UpdateBuilding {% endblock %}
{% block content %}
<!-- Update Building -->
<div class="container-fluid">
<div class="main-box">
<div class="row d-flex align-items-center justify-content-center">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex align-items-start flex-column">
<h1 class="mb-4 mt-2">Update Building</h1>
<form method="post" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="building_name" class="form-label">building name</label>
<input type="text" class="form-control form-control-lg" id="building_name" name="building_name" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="name_of_owner" class="form-label">name of owner</label>
<input type="text" class="form-control form-control-lg" id="name_of_owner" name="name_of_owner" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<label for="building_type" class="form-label">building type</label>
<select class="form-select form-select-lg mb-3" aria-label=".form-select-lg example" id="building_type" name="building_type">
<option selected>select</option>
{% for type in bldg_type %}
<option value="{{type.id}}">{{type.building_type}}</option>
{% endfor%}
</select>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="mobile_number" class="form-label">mobile number</label>
<input type="number" class="form-control form-control-lg" id="mobile_number" name="mobile_number">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-3">
<label for="number_of_rooms" class="form-label">number of rooms</label>
<input type="number" class="form-control form-control-lg" id="number_of_rooms" name="number_of_rooms">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="mb-5">
<label for="current_lease_period" class="form-label">current lease period</label>
<input type="date" class="form-control form-control-lg" id="current_lease_period" name="current_lease_period">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<button type="submit" class="btn btn-lg mb-4">Update</button>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<button type="reset" class="btn btn-lg">Reset</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}

Django Submitting two forms depending on each other with single submit button

I'm building a django app for managing orders. I have divided the orders management into two separated tables as follows:
Order: Fields include customer (Foreign Key), order_date, total_order_value and order_status.
OrderLine: Fields include item (Foreign Key), quantity, discount, total, order_id (Foreign Key).
I am trying to do the template for the order page such as below.
<div class="row mb-2 mt-2" style="text-align: center;">
<div class="col-2">
<input type=button value="Back" class="btn btn-secondary" onClick="javascript:history.go(-1);">
</div>
<div class="col-9"></div>
</div>
<form method="POST" action="" enctype="multipart/form-data" id= "test">
{% csrf_token %}
<form id="order" action="" method="POST" enctype="multipart/form-data"></form>
<form id="orderLine" action="" method="POST" enctype="multipart/form-data"></form>
<div class="card">
<div class="card-header" style="text-align: center;"><h1> Order Details </h1></div>
<div class="card-body">
<div class="card-text">
<div class="row">
<div class="col-md-6">
<label for="id" class="form-label">Order ID</label>
<input type="text" class="form-control" id="id" value="{{order.id}}" readonly>
</div>
<div class="col-6">
<label for="order_date" class="form-label">Order Date</label>
{{orderForm.order_date}}
</div>
<div class="col-6">
<label for="customer" class="form-label">Customer Name</label>
{{orderForm.customer}}
</div>
<div class="col-6">
<label for="status" class="form-label">Order Status</label>
{{orderForm.status}}
</div>
</div>
</div>
</div>
</div>
<div class="row">
<br>
</div>
<div class="card">
<div class="card-body">
<div class="card-text">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Unit Price</th>
<th scope="col">Quantity</th>
<th scope="col">Discount</th>
<th scope="col">Total</th>
</tr>
</thead>
{{ orderLineForm.management_form }}
<tbody>
{% for orderLine in orderLineForm %}
<tr class="orderline">
<th>{{orderLine.item}}</th>
<td>0</td>
<td>{{orderLine.qty}}</td>
<td class="omr" id="disc">{{orderLine.disc}}</td>
<td class="omr" id="total">{{orderLine.total_price}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="row">
<div class="col-10"></div>
<div class="col-2" style="text-align: right;">
<label for="total" class="form-label">Total</label>
{{orderForm.total}}
</div>
<div class="col-12"> <br></div>
{% if status == 'new' %}
<div class="col-12" style="text-align: center;">
<input type="submit" name="update" class="btn btn-success" value="Add" form="test">
</div>
{% else %}
<div class="col-6">
<input type="submit" name="update" class="btn btn-success" value="Update" form="orderLine">
</div>
<div class="col-6">
<input type="submit" name="delete" class="btn btn-danger" value="Delete" form="orderLine">
</div>
{% endif %}
</div>
</div>
</div>
</div>
</form>
views.py
def newOrder(request):
orderForm = OrderForm()
orderLineForm = formset_factory(OrderLineForm)
itemsList = list(Item.objects.values())
if request.method == 'POST':
orderForm = OrderForm(request.POST,prefix='0'),
orderLineForm = OrderLineForm(request.POST,prefix='1')
print(f'######\n form \n {request.POST}')
print(f'######\n order form \n {orderForm}')
print(f'######\n order line form \n {orderLineForm.data}')
return redirect('orders')
context = { 'orderForm':orderForm,
'orderLineForm':orderLineForm,
'status':'new',
'itemsList':itemsList,
}
return render(request,'orders/orderDetail.html',context=context)
When submitting the form I only get the data from one form and not from both. Also, I have to add the order ID to the OrderLine form before saving to database.
I would appreciate the support.

How to pass data from table of record to Modal

i know this question has been asked a lot, but all solution are not suitable for me.I essentially have a table inside a view that is displayed using a foreach loop in HTML and sqlalchemy ,this spits out the records one by one and appends some 'Action' buttons in the last column ( delete and edit),I just pass the ID in from each record in the foreach loop, then job done.
I'm having a lot of issues with my modal though, it only ever displays the data from the first record when I echo the data in the 'value' field of each input,I'm really stumped on how to make this functionality work (javascriptis not my strongest language), it's possible work without using Ajax and php?
i am using flask, python and sqlalchemy.
I think the issue is that the modal is only created once when the foreach loop starts running, hence why it only ever has the first record data inside the modal, any help to get around this so I can edit each individual record inside the table would be great! Thanks for the help.
my html code
{% extends "layout.html" %}
{% block title %}
Admin
{% endblock %}
{% block body %}
<h1> Admin</h1>
<div class="form-group">
<table border=1>
<tr>
<th>usa_order_id</th>
<th>user_id</th>
<th>cpu</th>
</tr>
{% for usa_order in usa_orders %}
<tr>
<th><input class="form-control" name ="usa_order_id" value={{usa_order.usa_order_id}}></th>
<th><input class="form-control" name ="user_id" value={{usa_order.user_id}}></th>
<th><input class="form-control" name ="cpu" value={{usa_order.cpu}}></th>
<th>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" >×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<input class="form-control" name ="usa_order_id" value=usa_order_id>
<input class="form-control" name ="user_id" value=user_id>
<input class="form-control" name ="cpu" value=cpu>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</th>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
my flask python code
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from model import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:xxx#localhost:3306/xxx'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
db = SQLAlchemy(app)
#app.route("/admin")
def index():
usa_order = usa_order.query.all()
return render_template("admin.html",usa_order = usa_order)
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0")
my model.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class usa_order(db.Model):
__tablename__ = "usa_order"
usa_order_id = db.Column(db.Integer,primary_key = True)
cpu = db.Column(db.String, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user.user_id"), nullable=False)
I think you'll need to give each Modal a unique ID, so it wouldn't be always superseded by the Modal generated first. Try the following HTML instead:
{% extends "layout.html" %}
{% block title %}
Admin
{% endblock %}
{% block body %}
<h1> Admin</h1>
<div class="form-group">
<table border=1>
<tr>
<th>usa_order_id</th>
<th>user_id</th>
<th>cpu</th>
</tr>
{% for usa_order in usa_orders %}
<tr>
<th><input class="form-control" name ="usa_order_id" value={{usa_order.usa_order_id}}></th>
<th><input class="form-control" name ="user_id" value={{usa_order.user_id}}></th>
<th><input class="form-control" name ="cpu" value={{usa_order.cpu}}></th>
<th>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal{{usa_order.id}}">
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal{{usa_order.id}}">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" >×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<input class="form-control" name ="usa_order_id" value=usa_order_id>
<input class="form-control" name ="user_id" value=user_id>
<input class="form-control" name ="cpu" value=cpu>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</th>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
NOTE: All i did there is to add the record ID to the Modal ID.

Why does this weird "content" attribute has no file associated with it error comes up in Django?

This question might have been asked several times before but I referred to them but I was not able to fix my problem. That is why I am having to ask it. So, I have a Django app where users can set up tasks. They can also upload attachments. I was successfully able to implement this but for some reason it has stopped working now. These are the relevant code:
models.py
def get_attachment_dir(instance, filename):
return f"users/{instance.parent_task.creator.username}_{instance.parent_task.creator.pk}/task_attachments/{instance.parent_task.pk}/{filename}"
class Attachments(models.Model):
content = models.FileField(null=True, blank=True, upload_to=get_attachment_dir, help_text="Add important documents or pictures")
parent_task = models.ForeignKey(ToDo, on_delete=models.CASCADE)
uploaded_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Attachments of {self.parent_task.title}"
forms.py
class TaskAttachmentForm(forms.ModelForm):
class Meta:
model = Attachments
fields = ["content"]
Relevant part of the view function that renders the attachment form
if request.method == "POST":
attachment_form = TaskAttachmentForm(request.POST, request.FILES)
if attachment_form.is_valid():
# Making sure we get no Integrity Errors
attachment_form.instance.parent_task = todo
attachment_form.save()
if not todo.has_attachments:
todo.has_attachments = True
todo.save()
messages.success(request, "Your files were uploaded successfully")
else:
attachment_form = TaskAttachmentForm()
attachments = Attachments.objects.filter(parent_task=todo)
context = {
"todo": todo,
"note_form": ToDoNotesForm(),
"note": note,
"subtask_form": SubTaskForm(),
"attachment_form": attachment_form,
"subtasks": subtasks,
"due_form": DueDateForm(),
"title": todo.title,
"percentage": percentage,
"attachments": attachments
}
return render(request, "ToDo/detailed_view.html", context=context)
detailed_view.html relevant code where attachments are handled
{% if attachments %}
<div id="attachments-section" class="table-responsive dark-mode-assist-section">
<table class="table dark-mode-assist-section">
<thead>
<tr>
<th>File</th>
<th>Uploaded on</th>
<th>View/Download</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for attachment in attachments %}
<tr class="list-group-item" id="attachment-{{ attachment.pk }}">
<td>{{ attachment.content|getfilename }}</td>
<td>{{ attachment.uploaded_on|date:"F d"}}</td>
<td><a class="btn btn-success" href="{{ attachment.content.url }}">Click me</a></td>
<td>
<button style="font-size: 2.5ch;" data-toggle="modal" data-target="#exampleModalCenter{{ attachment.pk }}" class="btn btn-outline-danger">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
<div class="modal fade" id="exampleModalCenter{{ attachment.pk }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content dark-mode-assist-section">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Confirm the deletion</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete this attachment?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button data-dismiss="modal" onclick="deleteItem('attachment', {{ attachment.pk }})" type="submit"
class="btn btn-danger">Yes, I am sure</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
<a class="btn btn-outline-info" data-toggle="collapse" href="#multiCollapseExample-attachments" role="button"
aria-expanded="false" aria-controls="multiCollapseExample">
Upload attachments
</a>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample-attachments">
<br>
<div class="card card-body dark-mode-assist-section">
<div class="content section">
<form method="POST" name="attachment-{{ todo.pk }}" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group dark-mode-assist">
<legend class="border-bottom mb-4">Add documents</legend>
{{ attachment_form|crispy }}
<input type="hidden" name="title" value={{ todo.pk }}>
<p id="hidden-parent-task-pk" style="display:none">{{ todo.pk }}</p>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info btn-lg" type="submit"><i class="fas fa-upload"></i></button>
</div>
</form>
</div>
</div>
</div>i
</div>
</div>
I am saying that this seems weird is because I was able to access attachment.content when running the same command under python manage.py shell
Any help is seriously appreciated and needed. Thanks a lot.

How to send data to view from form after asking for confirmation?

I created a simple form where I'm asking for user input and then posting that to the database. Now I would like the user to confirm the data in form is correct, and for that I'm using a Bootstrap modal.
How can I send the data from the form to the view when pressing the 'OK' button on the modal.
I'm new to the Django framework, and maybe there is another better way without using bootstrap modals.
Form:
class ReportForm(forms.Form):
report_title = forms.ChoiceField(choices=get_report_titles())
report_link = forms.CharField(widget=forms.Textarea, required=False)
Html file:
<form class="w-100" action="" method="post">
{% csrf_token %}
<label class="pl-0 mt-auto mr-2">Report Name</label>
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option>{{ name }}</option>
{% endfor %}
</select>
<div class="my-1 col-lg-12 float-left pl-0">
<label>Report Link</label>
<input class="form-control bg-white" type="text" id="report" name="report_link">
</div>
<input id="confirm" value="Save" type="button" data-toggle="modal" data-target="#exampleModalCenter" class="btn btn-outline-success" />
</form>
<!-- Modal -->
<div class=" modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Make sure you have the right title and link.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
View:
def report_view(request):
if request.method == 'POST':
form = ReportForm(request.POST)
if form.is_valid():
report_title = form.cleaned_data['report_title']
report_link = form.cleaned_data['report_link']
new_report = Report(title = report_title, link = report_link)
new_report.save()
Simply update your code with these lines, add id="exampleForm".
start form tag with
<form class="w-100" action="" id="exampleForm" method="post">
Replace Save button with (add id="save"):
<button type="button" id="save" class="btn btn-primary">Save</button>
and finally add this script at the bottom to submit your form when save is clicked:
<script>
$("#save").on("click", function(e) {
$("#exampleForm").submit();
});
</script>
also I feel your view is not written correctly. It should be something like this, I'm not sure what you're trying to do:
def report_view(request):
if request.method == 'POST' and form.is_valid():
form = ReportForm(request.POST)
report_title = form.cleaned_data['report_title']
report_link = form.cleaned_data['report_link']
new_report = Report(title = report_title, link = report_link)
new_report.save()
Let me know if you still need help
This needs changing because you're not giving any values.
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option>{{ name }}</option>
{% endfor %}
</select>
Try:
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option value="{{name.pk}}">{{ name }}</option>
{% endfor %}
</select>
where name.pk is the value relating to the choices.
Also, if you change your form to a ModelForm you can just do:
if form.is_valid():
new_report = form.save()

Categories