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 %}
Related
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.
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.
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'))
I have a model 'Manifests' and a form 'CreateManifestForm'. The user enters multiple lines of data in the CreateManifestForm and these are saved to the Manifest model (on a line by line basis, not using ajax or anything).
There are 3 fields of concern in the model and form - 'Cases', 'FOB', 'CNF'. Both FOB and CNF are dollar amounts, so I'll use one as an example. How could I take the user entered FOB price, multiply it by cases and then store that number? Additionally, when the user enters another line, how could I do the same and then add that to the original number so I can get a total value.
MODELS.PY
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
product_name = models.ForeignKey(Products, default=None, blank=True, null=True)
count = models.IntegerField()
CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True)
FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True)
def __str__(self):
return self.description
VIEWS.PY
def add_manifest(request, reference_id):
form = CreateManifestForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
instance.reference = order
except Orders.DoesNotExist:
pass
instance.save()
form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)})
reference = request.POST.get('reference')
manifests = Manifests.objects.all().filter(reference=reference)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
ADD_MANIFEST.HTML
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form id="create_mani_form" method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.FOB }}
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"-->
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th style="width:2%;"</th>
<th style="width:10%;">Ref ID</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
<th style="width:10%">FOB</th>
<th style="width:10%">CNF</th>
</tr>
</thead>
<tbody>
{% for manifests in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifests.reference }}</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.product_name}}</td>
<td>{{ manifests.count}}</td>
<td>{{ manifests.FOB}}</td>
<td>{{ manifests.CNF}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
Subit Manifest
</div>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
I would like to see a read-only field or something of that nature (I guess in the template) which shows the total for this particular manifest the user is creating. Any thoughts?
You can annotate the manifest objects with a computed field
from django.db.models import F, ExpressionWrapper
manifests = Manifests.objects.filter(
reference=reference
).annotate(
total=ExpressionWrapper(F('cases') * F('CNF'), output_field=DecimalField())
)
Then in your template you can reference manifest.total.
I am trying to make a business card manager using django python but I don't why my business card is not being added. When I press the button "Add business Card", it goes to the BusinessCardListView but it is blank. I also want to know how to make the delete and update button work on the Business Card List. I think I have to add a primary key in the model but I don't know how to pass it correctly.
Views
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
from .models import BusinessInfo
class BusinessCardListView(generic.ListView):
model = BusinessInfo
template_name = 'manager/BusinessCardList.html'
context_object_name = 'all_business_cards'
def get_queryset(self):
return BusinessInfo.objects.all()
class BusinessCardCreate(CreateView):
model = BusinessInfo
fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title',
'fax_number', 'cell_phone_number', 'email']
class BusinessCardUpdate(UpdateView):
model = BusinessInfo
fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title',
'fax_number', 'cell_phone_number', 'email']
class BusinessCardDelete(DeleteView):
model = BusinessInfo
success_url = reverse_lazy('manager:index')
Add Business Card form
{% extends 'manager/base.html' %}
{% block title %}Add a New Business Card{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="{% url 'manager:index' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'manager/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add Business Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
form_template
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.error }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
urls
from django.conf.urls import url
from . import views
app_name = 'manager'
urlpatterns = [
url(r'^$', views.BusinessCardListView.as_view(), name='index'),
url(r'business_card/add/$', views.BusinessCardCreate.as_view(), name='business_card-add'),
url(r'business_card/(?P<pk>[0-9]+)/edit/$', views.BusinessCardUpdate.as_view(), name='edit'),
url(r'business_card/(?P<pk>[0-9]+)/delete/$', views.BusinessCardDelete.as_view(), name='delete'),
]
models
from django.db import models
from django.core.urlresolvers import reverse
# Business Card Info
class BusinessInfo(models.Model):
card = models.FileField(default='Picture')
company_name = models.CharField(max_length=100000, primary_key=True)
website = models.CharField(max_length=100000)
representative_name = models.CharField(max_length=100000)
branch_address = models.CharField(max_length=100000)
job_title = models.CharField(max_length=10000)
email = models.EmailField()
phone_number = models.CharField(max_length=100000)
fax_number = models.CharField(max_length=100000)
cell_phone_number = models.CharField(max_length=100000)
def get_absolute_url(self):
return reverse('manager:index')
def __str__(self):
return self.company_name + ':' + self.representative_name
Business Card List
{% extends 'manager/Base.html' %}
{% block body %}
<style>
table, th, .Info {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
</style>
<table style="width:100%">
<tr>
<th>Business Card</th>
<th>Company Name</th>
<th>Representative Name</th>
<th>Job Title</th>
<th>Branch Address</th>
<th>Website</th>
<th>Phone Number</th>
<th>Cell Phone Number</th>
<th>Email</th>
<th>Fax Number</th>
</tr>
{% for businessinfo in all_business_cards %}
<tr>
<td class="Info">{{ businessinfo.card }}</td>
<td class="Info">{{ businessinfo.company_name }}</td>
<td class="Info">{{ businessinfo.representative_name }}</td>
<td class="Info">{{ businessinfo.job_title }}</td>
<td class="Info">{{ businessinfo.branch_address }}</td>
<td class="Info">{{ businessinfo.website }}</td>
<td class="Info">{{ contactinfo.phone_number }}</td>
<td class="Info">{{ contactinfo.cell_phone_number }}</td>
<td class="Info">{{ contactinfo.email }}</td>
<td class="Info">{{ contactinfo.fax_number }}</td>
<td>
<form action="{% url 'music:delete' %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="company_name" value="{{ company_name }}"/>
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
The action attribute in your form tag inside the Business Card Create form template is {% url 'manager:index' %} which points to the BuisinessCardListView thats why it is taking you to the list view on submit.
To achieve what you want it should point the CreateView url, like this:
{% extends 'manager/base.html' %}
{% block title %}Add a New Business Card{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="{% url 'manager:business_card-add' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'manager/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add Business Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}