I'm trying to submit Django forms in Bootstrap 4 modals with AJAX, but it doesnt submit for some reason. When you click on the submit button it just closes the modal and nothing else happens. The content shows correctly in the modal body at least, but it just doesnt submit.
Here is my view
class GaasWaferDesignFormView(SuccessMessageMixin, AjaxTemplateMixin, CreateView):
template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form.html'
ajax_template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form_inner.html'
form_class = GaasWaferDesignForm
model = GaasWaferDesign
form = GaasWaferDesignForm()
success_url = reverse_lazy('engineering:gaas_wafer_design_list')
success_message = "Success!"
def form_valid(self, form):
object = form.save(commit=False)
object.created_by = self.request.user
object.save()
return super(GaasWaferDesignCreateView, self).form_valid(form)
And here is my template which has the modal structure and button for the modal(gaas_wafer_design_list.html)...
{% extends "pages/list_template.html" %}{% load static from staticfiles %}
{% load widget_tweaks %}
{% block title %}GaAs Wafer Design List{% endblock %}
{% block list_title %}GaAs Wafer Designs{% endblock %}
{% block list_title_2 %}Design Inventory{% endblock %}
{% block extra_js%}
{% endblock %}
{% block buttons %}
<div class="btn-group" role="group" aria-label="Button group with nested dropdown" style="margin-bottom: -150px; z-index:1000;">
<button class="btn btn-secondary" data-toggle="modal" data-target="#form-modal" id="create-button">Create a new wafer design</button>
<div class="btn-group" role="group">
<a id="btnGroupDrop1" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
View
</a>
<div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<a class="dropdown-item" href="#">Recycling Bin</a>
</div>
</div>
</div>
{% endblock %}
{% block table %}
<div class="modal fade" id="form-modal" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Wafer Design</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
</div>
<div id="form-modal-body" class="modal-body">
</div>
</div>
</div><!-- /.modal-dialog -->
</div>
<thead>
<tr>
<th>
Wafer Design UI
</th>
<th>
Emitting Type
</th>
<th>
Contact Location
</th>
<th>
Optical Power
</th>
<th>
Design Date
</th>
<th>
Designer
</th>
<th>
Designer UI
</th>
<th>
Created At
</th>
</tr>
</thead>
<tfoot>
<tr>
<th>
Wafer Design UI
</th>
<th>
Emitting Type
</th>
<th>
Contact Location
</th>
<th>
Optical Power
</th>
<th>
Design Date
</th>
<th>
Designer
</th>
<th>
Designer UI
</th>
<th>
Created At
</th>
</tr>
</tfoot>
<tbody>
{% for gaas_wafer_design in gaas_wafer_designs %}
<tr>
<td>{{ gaas_wafer_design.design_ui }}</td>
<td>{{ gaas_wafer_design.get_emitting_display }}</td>
<td>{{ gaas_wafer_design.contact_location }}</td>
<td>{{ gaas_wafer_design.optical_power }}</td>
<td>{{ gaas_wafer_design.design_date|date:"m/d/y" }}</td>
<td>{{ gaas_wafer_design.designer }}</td>
<td>{{ gaas_wafer_design.designer_ui }}</td>
<td>{{ gaas_wafer_design.created_at }}</td>
</tr>
{% endfor %}
</tbody>
<script>
var formAjaxSubmit = function(form, modal) {
$(form).submit(function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (xhr, ajaxOptions, thrownError) {
if ( $(xhr).find('.has-error').length > 0 ) {
$(modal).find('.modal-body').html(xhr);
formAjaxSubmit(form, modal);
} else {
$(modal).modal('toggle');
}
},
error: function (xhr, ajaxOptions, thrownError) {
// handle response errors here
}
});
});
}
$('#create-button').click(function() {
$('#form-modal-body').load('create/', function () {
$('#form-modal').modal('toggle');
formAjaxSubmit('#form-modal-body form', '#form-modal');
});
});
</script>
{% endblock %}
Here is my url...
url(r'^gaas-wafer-designs/create/$', gaas_wafer_designs.GaasWaferDesignFormView.as_view(), name='gaas_wafer_design_create'),
And lastly here is my gaas_wafer_design_form_inner.html (template which has the modal body content)
{% load widget_tweaks %}
<form method="post" action="{% url 'engineering:gaas_wafer_design_create' %}">{% csrf_token %}
<div class="row">
<div class="form-group col-sm-12">
<div class="form-group">
<label for="{{ form.design_ui.id_for_label }}"><b>Design UI</b></label>
{% render_field form.design_ui class+="form-control" %}
{{ form.design_ui.errors }}
</div>
</div>
</div>
<!--/.row-->
<div class="row">
<div class="form-group col-sm-4">
<div class="form-group">
<label for="{{ form.emitting.id_for_label }}"><b>Emitting</b></label>
{% render_field form.emitting class+="form-control" %}
{{ form.emitting.errors }}
</div>
</div>
<div class="form-group col-sm-4">
<div class="form-group">
<label for="{{ form.contact_location.id_for_label }}"><b>Contact Location</b></label>
{% render_field form.contact_location class+="form-control" %}
{{ form.contact_location.errors }}
</div>
</div>
<div class="form-group col-sm-4">
<div class="form-group">
<label for="{{ form.optical_power.id_for_label }}">Optical Power</label>
{% render_field form.optical_power class+="form-control" %}
{{ form.optical_power.errors }}
</div>
</div>
</div>
<!--/.row-->
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save changes" />
</form>
Thanks for any help you can give!
I believe that the object is created, but your form_valid doesn't return to the success_url. At the end of your form_valid you should redirect to success_url. I don't understand what you're trying to achieve with your return at the end of form_valid.
def form_valid(self, form):
...
return HttpResponseRedirect(self.get_success_url())
And you can than also override success_url and add massage if needed.
def get_success_url(self):
# add message
messages.add_message(self.request, messages.SUCCESS, 'Your message.')
# reverse back to providers' page with success message
return reverse_lazy('engineering:gaas_wafer_design_list')
I have written a simple to use package for such functionalities and you can check it out at django-bootstrap-modal-forms.
Related
How do I pass the value from the inside of a for loop ( jinja2 ) to a bootstrap modal to display it in side the modal body?
here is my views.py file:
if request.method == 'GET':
driver = get_network_driver(device.napalm_driver)
with driver(device.IP_address, device.username, device.password) as device_conn:
interfaces = device_conn.get_interfaces()
context = {
'device': device,
'interfaces': interfaces,
}
return render(request, 'network/interface_list.html', context)
Please note that the the device_conn.get_interfaces() method returns a nested dictionary.
Here is the html template:
{% extends 'base/base.html' %}
{% block title %}iNet Interface List{% endblock %}
{% block content %}
<div class="section">
{% include 'network/include/interface_list_header.html' %}
{% if messages %}
{% for message in messages %}
{% if message.tags == 'success' %}<div class="alert alert-success" role="alert">
{{ message }}
</div>{% elif message.tags == 'error' %}<div class="alert alert-danger" role="alert">
{{ message }}
</div>{% endif %}
{% endfor %}
{% endif %}
<div class="card mx-auto shadow rounded">
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col" style="text-align:center">Interface Name</th>
<th scope="col" style="text-align:center">Admin status</th>
<th scope="col" style="text-align:center">Protocol</th>
<th scope="col" style="text-align:center">Description</th>
<th scope="col" style="text-align:center">MAC Address</th>
<th scope="col" style="text-align:center">Last Flapped</th>
<th scope="col" style="text-align:center">Turn On/Off Port</th>
<th scope="col" style="text-align:center">Edit Description</th>
</tr>
</thead>
<tbody>
{% for interface_name, interface in interfaces.items %}
<tr>
<form action="{% url 'get_interfaces' device.id %}" method="post" id="{{ interface_name }}">
{% csrf_token %}
<input type="hidden" value="{{ interface_name }}" name="interface_name" />
<input type="hidden" value="{{ interface.is_enabled|yesno:'False,True' }}" name="enable" />
</form>
<td style="text-align:center">{{ interface_name }}</td>
<td style="text-align:center">{% if interface.is_enabled %}<i class="fa-solid fa-check text-success"></i>{% else %}<i class="fa-solid fa-xmark text-danger"></i>{% endif %}</td>
<td style="text-align:center">{% if interface.is_up %}<i class="fa-solid fa-check text-success"></i>{% else %}<i class="fa-solid fa-xmark text-danger"></i>{% endif %}</td>
<td style="text-align:center">{{ interface.description }} </td>
<td style="text-align:center">{{ interface.mac_address }}</td>
<td style="text-align:center">{{ interface.last_flapped }}</td>
<td style="text-align:center"><button class="btn common-button btn-primary" type="submit" form="{{ interface_name }}" value="Submit">{% if interface.is_enabled %}Turn Off{% else %}Turn On{% endif %}</button></td>
<!-- Modal Trigger button -->
<td style="text-align:center"><i class="fa-regular fa-clipboard"></i></td>
<!-- Modal container -->
<div class="modal fade viewModal" id="editDesc{{ interface_name }}" tabindex="-1" role="dialog" aria-labelledby="editDescLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 style="font-size: 20px;" class="modal-title" id="editDescLabel">View Console Output</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<textarea>{{ interface.description }}</textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
I wish to show the {{interface.description}} of the selected interface in the textarea so that I can edit it later. Any help would be appreciated.
My issue is - I am able to fetch {{interface.description}} outside the bootstrap modal, however I am unable to fetch the same thin inside the bootstrap modal. Eventhough both of them are inside the for loop.
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys?
views.py
#login_required(login_url="admin-login")
#user_passes_test(check_role_admin)
def colorProductMap_edit(request, id):
instance = ColorProductMapping.objects.get(color_p_map_id=id)
print(instance.color_id)
form = ColorProductMapForm(instance=instance)
if request.method == 'POST':
form = ColorProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/colorProductMap')
else:
form = ColorProductMapForm(instance=instance)
return render(request, 'admin1/colorProductMap.html', {'form': form, 'instance': instance})
I properly partnered and connected with the following in my urls.py.
urls.py
path('colorProductMap_edit/<int:id>', views.colorProductMap_edit, name="admin-color-product-map-edit"),
forms.py
class ColorProductMapForm(forms.ModelForm):
class Meta:
model = ColorProductMapping
fields = ['color_id', 'prod_id']
models.py
class ColorProductMapping(models.Model):
color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
colorProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Color Product Map{% endblock %}
{% block main %}
<h1>
<center>Color Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{%if colorProductMap_show%}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Color Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Color Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-color-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<div class="modal-footer justify-content-right">
<input type="Submit" name="Submit" value="Submit" class="btn btn-outline-success">
<button type="button" class="btn btn-outline-danger" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Color Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Color Product Mapping Id</th>
<th>Product ID</th>
<th>Color ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in colorProductMap_show %}
<tr>
<td>{{x.color_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.color_id}}</td>
<td><a href="{% url 'admin-color-product-map-edit' x.color_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-color-product-map-delete' x.color_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if colorProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in colorProductMap_show.paginator.page_range %}
{% if colorProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if colorProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{%endif%}
{% if instance %}
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
What am I doing wrong? I think I have followed every advice I could find, but yeah it still gives me the error. Any help is appreciated. Thank you very much!
You write your form tag as:
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
After observing your template and view it appears that you are using the same template for multiple views and this is causing confusion. As I note in the comment there is no x in the context for this view (In the other one you loop over a variable which doesn't exist in this view to get this). After looking a bit more one notices that by this {% url 'admin-color-product-map-edit' x.color_p_map_id %} you want to point to the current url itself. If a forms action is to the same url the best thing to do is forego the action attribute completely (If there is no action attribute the request would be to the same url as the page user is in):
<form method="POST" enctype="multipart/form-data">
Thanks all to guide me, I have found my mistake.
In the html template, as shown below
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
Here I am using x.color_p_map_id where x is not any iterable object so the error I was getting.
Now I have made a change and used instance instead of x in above url and now its working fine.
<form action="{% url 'admin-color-product-map-edit' instance.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
I am working on a testing app that lists out users from the database in a HTML table, what I want to achieve is this, when you click on any icon for a particular record or row the full detail of that record is displayed in a Bootstrap Modal. My problem is how do I implement my views, urls, and also my Templates? Do I need Javascript help here? Cause in PHP this is done easily without JavaScript. Plesae I will prefer code samples as a correction to my issue thanks.
Here is my view
def users(request):
get_users = User.objects.all()
return render(request, 'classwork_app/users.html', {'users':get_users})
My urls
from classwork_app import views
app_name = 'classwork_app'
urlpatterns = [
path('', views.users, name='users'),
]
Templates
<table class="table table-bordered">
<tr>
<th>S/N</th>
<th>Username</th>
<th>Firstname</th>
<th>Lastname</th>
<th colspan="2">Action</th>
</tr>
{% if users %}
{% for u in users %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ u.username }}</td>
<td>{{ u.first_name }}</td>
<td>{{ u.last_name }}</td>
<td style="font-size: 12px"><a data-toggle="modal" href="#MyModal{{ u.id }}"><i class="fa fa-eye"></i></a></td>
</tr>
{% endfor %}
{% endif %}
</table>
<div id="#MyModal{{ u.id }}" 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">{{ u.first_name }} {{ u.last_name }}</h4>
</div>
<div class="modal-body">
<p>
Username: {{ u.username }}
Firstname: {{ u.first_name }}
Lastname: {{ u.last_name }}
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
you can try putting your modal html code inside the for user iterator. This way it will load a modal with user content for every user in your list (not very recommended if you have a lot of data, can cause performance issues)
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 attempting to populate a table with a filtered set of data from my Manifests model using a url parameter.
I believe that the problem I am having is in the Views.py line
manifests = Manifests.objects.all().filter(reference=reference_id)
Models.py
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
description = models.CharField(max_length=1000)
count = models.IntegerField()
def __str__(self):
return self.description
Urls.py
url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'),
Views.py
def add_manifest(request, reference_id):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
except Orders.DoesNotExist:
pass
instance.reference = order
instance.save()
return redirect('add_manifest', reference_id=reference_id)
form = CreateManifestForm()
#manifests = Manifests.objects.all()
manifests = Manifests.objects.all().filter(reference=reference_id)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
template (add_manifest.html)
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference">Reference ID: </label><br>
<input type="text" value="{{ reference_id }}">
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description">Description: </label>
<br>
{{ form.description}}
</div>
</div>
<div class="column">
<label for="form.cases">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count">Count: </label>
<br>
{{ form.count }}
<br>
<br>
</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 class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th></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>
</tr>
</thead>
<tbody>
{% for manifests in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifests.reference }}</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.description}}</td>
<td>{{ manifests.count}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" name="button" align="right">Subit Manifest</button>
</div>
</div>
I want the table to display only lines where the reference in the Manifests model = the reference_id in the URL. Currently it does not work as such, the table is just empty.
Change the for-loop variable name like this:
{% for manifest in manifests %}
<tr>
<td>
Edit
</td>
<td>{{ manifest.reference }}</td>
<td>{{ manifest.cases }}</td>
<td>{{ manifest.description}}</td>
<td>{{ manifest.count}}</td>
</tr>
{% endfor %}
If there is any Manifest object for reference_id, then it will render them in template.
Update
Its possible that your form is not validating. So its a good idea to render form errors:
# view
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()
manifests = Manifests.objects.all().filter(reference=reference_id)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
And update template to show the errors in template as well:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}