Get pk_id using function based view - python

I'm having a problem in getting the pk in my template. When I select a record it always returns the last pk ID. Btw, I'am using functional base view. Here's my collection.html:
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
<table class="table" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Download</th>
</tr>
</thead>
<tbody>
{% for collectionlist in collection %}
<tr>
<td>{{ collectionlist.id }}</td>
<td>{{ collectionlist.sqa_name }}</td>
<td>{{ collectionlist.status }}</td>
<td class="center"><center><button type="button" class="btn btn-link" data-toggle="modal" data-target="#myModaldl{{ collectionlist.id }}" ><span class="glyphicon glyphicon-download-alt"></span></button></center></td>
</tr>
<div class="modal fade collectClass" id="myModaldl{{ collectionlist.id }}" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Single Collect</h3>
</div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label for="inputSQAID" class="col-sm-3 control-label">SQA Name</label>
<div class="col-sm-8">
<input type="hidden" name="pk_id" id="pk_id" value="{{ collectionlist.id }}">
<input type="text" class="form-control" name="singlecollect" value="{{ collectionlist.sqa_name }}" id="inputSQAID">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" name="single_dl">Download</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</form>
Here's my views.py:
def collection(request):
context = {
'collection': DataCollection.objects.all(),
'title': 'Data Collection',
}
return render(request, 'data_collection/collection.html', context)
def single_collect(request):
if request.method == 'POST':
pkid = request.POST.get('pk_id')
print(pkid)
all_data = DataCollection.objects.all()
return render(request, 'data_collection/collection.html', {'title' : 'Data Collection', 'data': all_data})
In my views.py, I just want first to print the pk ID of the item/record I selected in my table using the modal. But, it's always getting the last record in my database.

This is because you have a single <form> tag with all the DataCollection rows inside. You should have individual forms for each one, i.e.:
{% for collectionlist in collection %}
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
...
</form>
{% endfor %}

Related

How to Submit and Retrieve data in one view in Django?

I have a little confusion in my app.
I have an HTML page in which I have added one form (form data submitting) and one table (to display the submitted data).
For which I have a view that submit and retrieve the data at the same time but unfortunately, data is successfully storing in the table but in retrieving time, it gives me the error which is mentioned below.
Error
NoReverseMatch at /staff/add_staff_type
Reverse for 'student_profile' with keyword arguments '{'id': ''}' not
found. 1 pattern(s) tried: ['student/profile/(?P[0-9]+)$']
Views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime)
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("student/Add_Student", views.Add_Student, name="Add_Student"),
path("student/display_students", views.Display_Student, name="display_students"),
path("student/edit/<int:id>", views.student_edit, name="student_edit"),
path("student/update/<int:id>", views.student_update, name="student_update"),
path("student/profile/<int:id>", views.student_profile, name="student_profile"),
path("student/delete/<int:id>", views.student_delete, name="student_delete"),
#below url is for staff_type on which i am currently workin
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
]
staff_type.html
<div class="card">
<div class="card-header">
<h3 class="card-title">Add Staff Type</h3>
</div>
<!-- /.card-header -->
<!-- form start -->
<form
class="needs-validation"
action="add_staff_type"
method="POST"
enctype="multipart/form-data"
novalidate
>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">Designation</label>
<input
type="text"
class="form-control"
id="validationCustom01"
placeholder="Acountant, Librarian, Teacher"
name="designation"
required
/>
<div class="valid-feedback">Looks good!</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom04">Salary</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Rs.</span>
</div>
<input type="number" class="form-control" id="validationCustom04" name="salary" min="0">
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom03">Date and Time</label>
<input
type="datetime-local"
class="form-control"
id="validationCustom03"
placeholder="MM/DD/YYY"
name="datetime"
required
/>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<!--
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustomUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
-->
<button class="btn btn-primary" type="submit">Add Staff Type</button>
</div>
</form>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Available Staff Types</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Designation</th>
<th>Salary</th>
<th>Entry Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for staff_type in display_staff_type %}
<tr>
<td>{{staff_type.designation}}</td>
<td>{{staff_type.salary}}</td>
<td>{{staff_type.datetime}}</td>
<td>
<a href="{% url 'student_profile' id=student.id %}">
<i class="far fa-eye"></i>
</a>
<a href="{% url 'student_edit' id=student.id %}">
<i class="far fa-edit"></i>
</a>
<a href="{% url 'student_delete' id=student.id %}">
<i class="far fa-trash-alt"></i>
</a>
</td>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
You can revise your view function to this:
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime)
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
# this can also be return redirect('staff:add_staff_type')
return redirect('add_staff_type')
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
Since you are calling the same view and serving data to the same form and view you can remove the action value of the form which goes like this:
<form
class="needs-validation"
action=""
method="POST"
enctype="multipart/form-data"
novalidate
>

why the form is invalid on post

I have records in my model. I want to list the existing records and edit and add more records. I successfully got the records to my template and edit. I can add new records also. it is working fine in template. But when I post the form is invalid and print invalid message as per my code http response. I can not figure out what is the mistake. Please advise.
forms.py:
class NewTransForm(forms.ModelForm):
th_no = forms.DecimalField(max_digits=5,error_messages={"max_digits":"Transaction number
should be less than 6 digits.","unique":"Transaction number already exists."})
class Meta:
model = TransHeader
fields = ['th_no','th_dt','th_type', 'th_code','th_cust_code','th_sm_code','th_ref']
...
urls.py:
path('edit_sales_transaction_details/<int:trans_id>/',views.EditSalesTransaction,
name="edit_sales_transaction"),
views.py:
def EditSalesTransaction(request,trans_id):
# template_name= "wstore/edit_sales_transheader_input.html.html"
# trans_id =kwargs['trans_id']
if request.method == "POST":
print(request.POST)
form = NewTransForm(request.POST)
if form.is_valid():
# trans_id =kwargs['trans_id']
exist_trans_header = TransHeader.objects.get(id=int(trans_id))
TransBody.objects.filter(trans_header=exist_trans_header).delete()
exist_trans_header.delete()
obj = form.save()
books = request.POST.getlist('book_code')
quantities = request.POST.getlist('quantity')
prices = request.POST.getlist('price')
for book_code,quantity,price in zip(books,quantities,prices):
try:
book = TextBook.objects.get(code=book_code)
TransBody.objects.create(trans_header_id=obj.id,quantity=quantity,price=price,book=book)
except Exception as e:
print(e)
if request.POST.get('save_home'):
return redirect('saltransactions')
else:
print(NewTransForm.errors)
# return redirect(reverse('view_sales_transaction', kwargs=kwargs['trans_id']))
return HttpResponse("form is invalid.. this is just an HttpResponse object")
else:
form = NewTransForm()
context = {}
# trans_id =kwargs['trans_id']
context['trans_header'] = TransHeader.objects.get(id=int(trans_id))
trans_body = TransBody.objects.filter(trans_header=context['trans_header'])
context['trans_body'] = trans_body
context['total_quantity'] = trans_body.aggregate(Sum('quantity'))
context['total_price'] = trans_body.aggregate(Sum('price'))
context['current_date'] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d")
context['form'] = form
return render(request, 'wstore/edit_sales_transheader_input.html', context)
...
edit_sales_transheader_input.html:
{% block content %}
<form action="" method="post" class="w-auto" id="new_trans_form"
xmlns:width="http://www.w3.org/1999/xhtml">
<div class="row mt-1 mb-4" >
<div class="col-md-12">
<div>
<div class="headerctr">
<h3>Sales</h3>
<!-- <div> -->
<!-- <h3 > -->
<!-- </h3> -->
</div>
<div class="card-body">
{% csrf_token %}
<div 38rem class="row style= width:18">
<div class="col">
<label>Transaction Date</label>
<input type="date" class="form-control" name="{{form.th_dt.name}}"
value="{{current_date}}"
readonly>
{% if form.th_dt.errors %}
{% for error in form.th_dt.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col-sm" >
<label>Transaction Number</label>
<input type="number" class="form-control" name="{{form.th_no.name}}"
value="{{trans_header.id}}" readonly>
{% if form.th_no.errors %}
{% for error in form.th_no.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Type</label>
<input type="hidden" class="form-control" name="{{form.th_type.name}}"
required readonly
value="INV">
{% if form.th_type.errors %}
{% for error in form.th_type.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
<label>Transaction Ref.</label>
<input type="text" class="form-control" name="{{form.th_ref.name}}" required
value="{{trans_header.th_ref}}">
{% if form.th_ref.errors %}
{% for error in form.th_ref.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
</div>
<div class="row mt-0">
<div class="col">
<label>Transaction Code</label>
<input type="text" class="form-control" name="{{form.th_code.name}}" required
readonly
value="POS INV">
{% if form.th_code.errors %}
{% for error in form.th_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Customer Code</label>
<input type="text" class="form-control" name="{{form.th_cust_code.name}}"
required
value="{{trans_header.th_cust_code}}">
{% if form.th_cust_code.errors %}
{% for error in form.th_cust_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Salesman</label>
<input type="text" class="form-control" name="{{form.th_sm_code.name}}"
required
value="{{trans_header.th_sm_code}}">
{% if form.th_sm_code.errors %}
{% for error in form.th_sm_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 mt-0">
<div class="card shadow">
<div class="card-header text-center">
<h3 class="headerctr">
Item Details
</h3>
</div>
<div class="card-body">
{% csrf_token %}
<table class="">
<thead class="thead-light">
<tr>
<th>Code</th>
<th class = "text-danger">Description</th>
<th>Quantity</th>
<th class = "text-danger">Price</th>
<th class="text-success">Total Price</th>
<th class = "text-warning">Actions</th>
</tr>
</thead>
<tbody id="books_list" style="margin-bottom: 0">
{% for book in trans_body %}
<tr>
<td>
<input type="text" name="book_code" class="form-control
book_code"
placeholder="Book Code" value="{{book.book.code}}"
required>
</td>
<td>
<input type="text" name="book_name" class="form-control
book_name"
placeholder="Book Name" value="{{book.book.name}}"
readonly>
</td>
<td>
<input type="number" class="form-control quantity"
name="quantity"
placeholder="Quantity" value="{{book.quantity}}"
required>
</td>
<td>
<input type="text" class="form-control org_price"
placeholder="Price"
value="{{book.price}}" readonly >
</td>
<td>
<input type="hidden" class="org_price">
<input type="text" class="form-control price" name="price"
placeholder="Total Price"
value="{{book.price}}" readonly>
</td>
<td>
<div class="btn-group">
<button type="button" id="btnadd" class="btn add_new_row"
title="Add">
<i class="fas fa-plus-square"></i>
</button>
<button type="button" class="btn delete_row"
title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</td>
</tr>
{% endfor %}
<tr id="newitem">
<td>
<input type="text" name="book_code" class="form-control book_code"
placeholder="Book Code" required>
</td>
<td>
<input type="text" name="book_name" class="form-control book_name"
placeholder="Book Name" readonly>
</td>
<td>
<input type="number" class="form-control quantity" name="quantity"
placeholder="Quantity" value="0" required>
</td>
<td>
<input type="text" class="form-control org_price" placeholder="Price"
value="0" readonly>
</td>
<td>
<input type="hidden" class="org_price">
<input type="text" class="form-control price" name="price" placeholder="Total Price"
value="0" readonly>
</td>
<td>
<div class="btn-group">
<button type="button" id="btnadd" class="btn add_new_row"
title="Add">
<i class="fas fa-plus-square"></i>
</button>
<button type="button" class="btn delete_row" title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td class = "text-success">Total Quantity: <strong
id="final_quantity">0</strong></td>
<td></td>
<td class = "text-success"> Total Price: <strong
id="final_price">0</strong></td>
</tr>
</tfoot>
</table>
</div>
<div class="col-md-12 mb-1">
<div class="btn-group">
<a href="{% url 'saltransactions' %}" class="btn btn-info mr-2" >Cancel</a>
{# <input type="submit" class="btn btn-info mr-2" name="save_home"
value="Hold">#}
<input type="submit" class="btn btn-info submit_form" name="save_next"
value="Save&Print">
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
...

Passing Parameters From a Class Based View in Django

I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view?
views.py
class ManifestUpdate(BSModalUpdateView):
model = Manifests
template_name = 'manifest_update.html'
form_class = UpdateManifestForm
success_message = 'Success: Manifest was updated.'
success_url = reverse_lazy('manifest')
def manifest(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
reference_id = form.cleaned_data.get('reference')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
else:
reference_id = request.POST.get('Reference_Nos')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class UpdateManifestForm(BSModalForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
update_manifest.html
#showing the modal window body
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Manifest</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<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>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.product_name" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</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>
</div>
</div>
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
</form>
manifest_readonly.html
#showing the html rendered by the manifest view
{% extends 'base.html' %}
{% load humanize %}
{% block body %}
{% load staticfiles %}
<div class="container">
<div class="col-xs-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
<center>{{ message }}</center>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<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>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</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.reference" class="formlabels">Case Total: </label><br>
<input type="text" value="{{ total_cases|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total CNF: </label><br>
<input type="text" value="{{ totalCNF|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total FOB: </label><br>
<input type="text" value="{{ totalFOB|intcomma }}" readonly>
</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%;">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 data %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-manifest btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'manifest_update' manifests.pk %}">
<span class="fa fa-pencil"></span>
</button>
</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>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="jquery.min.js"></script>
<script src="jquery.fulltable.js"></script>
<script src="script.js"></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(function () {
$(".update-manifest").each(function () {
$(this).modalForm({formURL: $(this).data('id')});
});
});
</script>
{% endblock %}
jquery.bootstrap.modal.forms.js
(function ($) {
// Place the form at formURL to modalContent element of modal with id=modalID
var newForm = function (modalID, modalContent, modalForm, formURL, successURL, errorClass) {
$(modalContent).load(formURL, function () {
$(modalID).modal('toggle');
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
});
};
// Add AJAX validation to the modalForm
var ajaxSubmit = function (modalID, modalContent, modalForm, successURL, errorClass) {
$(modalForm).submit(function (event) {
// Prevent submit and POST form to url using AJAX
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
// Serialize form data
data: $(this).serialize(),
success: function (response) {
// Update form with errors after unsuccessful POST request
// Django form.is_valid() = False
if ($(response).find(errorClass).length > 0) {
$(modalID).find(modalContent).html(response);
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
}
// Hide modal after successful POST request when & redirect to successURL
else {
$(modalID).modal("hide");
window.location.href = successURL;
}
}
});
});
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
successURL: "/",
errorClass: ".invalid"
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
return this.each(function () {
$(this).click(function (event) {
newForm(settings.modalID,
settings.modalContent,
settings.modalForm,
settings.formURL,
settings.successURL,
settings.errorClass);
event.preventDefault();
});
});
};
}(jQuery));

Bootstrap modal not updating modal content

I am trying to create a table of models with a button next to them which opens a modal and has the same model row in form view. The table is being populated correctly, but the n number of bootstrap modals being created only hold the first iterable model value. Is it because bootstrap loads the content of the modals only once when the page is rendered ? What do I do to solve the problem ? Should I run a function to update the modal content according to the model data it has ??
Feel free to ask any more clarifications.
{% extends 'base.html' %}
{% load static %}
{% block content %}
<table>
{% for item in data %}
<tr>
<th>From</th>
<th>To</th>
<th>Weight</th>
<th>Length</th>
<th>Type</th>
<th>Material Type</th>
<th>Number of Trucks</th>
<th>Loading Time</th>
</tr>
<tr>
<td>{{ item.From }}</td>
<td>{{ item.To }}</td>
<td>{{ item.Weight }}</td>
<td>{{ item.Length }}</td>
<td>{{ item.Type }}</td>
<td>{{ item.MaterialType }}</td>
<td>{{ item.Numberoftrucks }}</td>
<td>{{ item.Loadingtime }}</td>
<td>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Bid
now! for id {{ item.id }} </button>
</td>
{# {% endfor %}#}
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.To }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.From }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Weight }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Length }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Type }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.MaterialType }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Numberoftrucks }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Loadingtime }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here...">Bid
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</tr>
{% endfor %}
</table>
{% endblock %}
you can fix it by add model.pk to the modal id
in the button
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal"
data-target="#myModal{{ item.id }}">
Bid now! for id {{ item.id }}
</button>
and in the
<div class="modal fade"
id="myModal{{ item.id }}"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
other solution is create js function to load new data to each time as you activate the modal.

Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name

I have a Django project in which the page that should load to show the album that has just been added, does not. It should go to the primary key for that album (auto generated) with the reference: http://127.0.0.1:8000/music/1/ but instead gives the error:
Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name.
A variant of the same problem, I assume, Is that when I click on the VIEW DETAILS BUTTON (shown below in the index.html) it doesn't load:
<div class="caption">
<h2>{{ album.album_title }}</h2>
<h4>{{ album.artist }}</h4>
<!-- View Details -->
View Details
<!-- Delete Album -->
<form action="#" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="album_id" value="{{ album.id }}" />
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
The code for the various sections is below:
music/templates/music/album_form.html
<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="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'music/form_template.html' %} <!-- how form fields and inputs are laid out-->
<div class="form-group>
<div class="col-sum-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
music/views.py
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .models import Album
#=============HOME PAGE===================
class IndexView(generic.ListView):
#specify template being used
template_name='music/index.html' #when we get a list of all albums, plug them into this template
context_object_name='all_albums' #if you don't use this variable it is automatically just object_list (which is used in index.html)
#make a query set
def get_queryset(self):
return Album.objects.all()
#=============DETAILS VIEW=============== details about one object
class DetailView(generic.DetailView):
#what model are we looking at /for
model=Album
template_name='music/detail.html'
#===============For the add album form
class AlbumCreate(CreateView):
model=Album
fields=['artist','album_title','genre','album_logo']
music/urls.py
from django.contrib import admin
from django.urls import include, path
from . import views #the dot means look at the current directory - look for a module called views
app_name='music'
urlpatterns = [
#this is matching /music/
path('', views.IndexView.as_view(), name='index'),
#when you use a detail view it expects a primary key
path("<pk>/", views.DetailView.as_view(), name="detail"),
#/music/album/add - dont need to specify pk
path('album/add/', views.AlbumCreate.as_view(), name="album-add"),
]
music/models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class Album(models.Model):
artist=models.CharField(max_length=250)
album_title=models.CharField(max_length=500)
genre=models.CharField(max_length=100)
album_logo=models.CharField(max_length=1000)
def __str__(self):
return self.album_title+""+self.artist
def get_absolute_url(self):
return reverse('music:detail',kwargs={'pk':self.pk})
#music detail takes the primary key ..
class Song(models.Model):
album=models.ForeignKey(Album, on_delete=models.CASCADE)
file_type=models.CharField(max_length=10)
song_title=models.CharField(max_length=250)
is_favorite = models.BooleanField(default=False)
def __str__(self):
return self.song_title
Update: also including details.py
{% extends 'music/base.html' %}
{% block title %}{{ album }}{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid songs-container">
<div class="row">
<!-- Left Album Info -->
<div class="col-sm-4 col-md-3">
<div class="panel panel-default">
<div class="panel-body">
<a href="{% url 'music:detail' album.id %}">
{% if album.album_logo %}
<img src="{{ album.album_logo.url }}" class="img-responsive">
{% else %}
<h3>No image to display</h3>
{% endif %}
</a>
<h1>{{ album.album_title }} <small>{{ album.genre }}</small></h1>
<h2>{{ album.artist }}</h2>
</div>
</div>
</div>
<!-- Right Song Info -->
<div class="col-sm-8 col-md-9">
<ul class="nav nav-pills" style="margin-bottom: 10px;">
<li role="presentation" class="active">View All</li>
<li role="presentation">Add New Song</li>
</ul>
<div class="panel panel-default">
<div class="panel-body">
<h3>All Songs</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<table class="table">
<thead>
<tr>
<th>Title</th>
<th>Audio File</th>
<th>Favorite</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for song in album.song_set.all %}
<tr>
<td>{{ song.song_title }}</td>
<td>
<a target="_blank" href="{{ song.audio_file.url }}">
<button type="button" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-play"></span> Play
</button>
</a>
</td>
<td>
<span class="glyphicon glyphicon-star {% if song.is_favorite %}active{% endif %}"></span>
</td>
<td>
<form action="{% url 'music:delete_song' album.id song.id %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="song_id" value="{{ song.id }}" />
<button type="submit" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-remove"></span> Delete
</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

Categories

Resources