How to display uploaded pdf file along with machine name and operation number based on select from dropdown - django

In this project, I want to display machine name and operation number along with uploaded pdf files based on select machine name and operation number from dropdown menu. This project is working but when I add and select another file in same machine name and operation number, it is displaying two pdf files along with previous pdf file of another machine name and operation number, exactly I don't want it. It should display machine name and operation number along with uploaded pdf file based on select from dropdown menu. And also when I upload another pdf files in same machine name and operation number, it should display two pdf files along with same machine name and operation number within same row.
This project is working fine but I want above validations.
Please anyone can help me out, this will be great for me. Please..
views.py:
def upload(request):
controlmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines})
def save_machine(request):
if request.method == "POST":
machine_name = request.POST.get('machinename', '')
operation_no = request.POST.get('operationname','')
choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no)
cmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines,'choiced_cmachine':choiced_cmachine})
def index(request):
if request.method == 'POST':
form = ControlmachineForm(request.POST, request.FILES)
if form.is_valid():
model_instance = form.save()
model_instance.save()
else:
form = ControlmachineForm()
controlmachiness = Controlmachine.objects.all()
return render(request,'usermaster/upload_file.html',{'form':form,'controlmachiness':controlmachiness})
upload.html:
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in controlmachines %}
view file
{% endfor %}
</td>
{% endfor %}
</tr>
control_uploadfile.html:
<html>
<head>
<title>Master File Upload</title>
</head>
<body>
<p><h1>Control File Upload</h1></p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button> <br><br>
</form>
</body>
</html>
control_show.html:
{% extends "master/control_base.html" %}
{% block title %}Control File{% endblock title %}
{% block content %}
<div class="col-md-12">
<div class="table-responsive">
<table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%">
<thead>
<th><input type="checkbox" id="checkall" /></th>
<th>ID</th>
<th>Machine Name</th>
<th>Operation Number</th>
<th>File</th>
<th>Delete</th>
</thead>
<tbody>
{% for control in controlmachines %}
<tr>
<td><input type="checkbox" class="checkthis" /></td>
<td>{{ control.id }}</td>
<td>{{ control.machine_name }}</td>
<td>{{ control.operation_no }}</td>
<td>{{ control.control_uploadfile }}</td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete"></span></p></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock content %}
models.py:
class Controlmachine(models.Model):
machine_name = models.CharField(max_length=100)
operation_no = models.IntegerField()
control_uploadfile = models.FileField(upload_to='documents/')
class Meta:
db_table = "controlmachine"
forms.py:
class ControlForm(forms.ModelForm):
class Meta:
model = Controlmachine
fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }),
'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }),
'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }),
}

Do this: Here I have added if condition that is used to connect machine name to uploaded file.
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in controlmachines %}
{% if file == choice and file == choice %}
view file
{% endif %}
{% endfor %}
</td>
{% endfor %}
</tr>

Related

HTMX form submission produces a duplicate form

{% extends "IntakeApp/base3.html" %}
{% load static %}
{% load crispy_forms_tags %}
{% block heading %}
<h2>Allergies for {{request.session.report_claimant}}</h2>
{% endblock %}
{% block content %}
<form hx-post="{% url 'allergy' %}" hx-target="#allergy_target" hx-swap="outerHTML">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-2 mb-0">
{{ form.allergen|as_crispy_field }}
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
<div class="container-fluid">
<table class="table table-striped table-sm" id="med-table">
<thead>
<tr>
<th>Allergen</th>
</tr>
</thead>
<tbody id="allergy_target">
{% for allergy in allergy_list %}
<tr>
<td>{{allergy.allergen}}</td>
<td>
<form method="POST" action="{% url 'allergy-delete' allergy.id %}">{% csrf_token %}
<input class="btn btn-danger btn-sm" type="submit" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
class AllergyCreateView(generic.CreateView):
model = Allergy
template_name = 'IntakeApp/allergy_form.html'
form_class = AllergyForm
def form_valid(self, form):
form.instance.assessment = Assessment.objects.get(id=self.request.session['assessment_id'])
return super(AllergyCreateView, self).form_valid(form)
def get_success_url(self):
return reverse_lazy("allergy")
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
assessment_id = self.request.session['assessment_id']
allergy_list = Allergy.objects.filter(assessment=assessment_id)
context["allergy_list"] = allergy_list
return context
I tried to all the different hx-swap options, but none fix it...It does post correctly and the swap does work, just not sure why I am getting another form in there. Please help
I added the View above. I think thats were my issue is...not sure if I am supposed to be doing this way or not?
Seems like you're trying to render the same html content in your view, which instead should only take a specific element.
You can try to use hx-select="#allergy_target" so htmx will only fetch the table content.

displaying None instead of data in the form of table

Here, select machine name and operation number, after select and save, It is displaying none instead of data like machine name and operation number in the form of table.
Please help me out to solve this.
I am new in Django.
urls.py:
urlpatterns = [
path('upload/',views.upload,name='upload'),
path('save',views.save_machine,name='save_machine')
]
views.py:
def upload(request):
machines = Machine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines})
def save_machine(request):
if request.method == "POST":
machine_name = request.POST.get('machine_name', '')
operation_no = request.POST.get('operation_no')
choiced_machine = Machine.objects.get(machine_name=machine_name, operation_no=operation_no)
machines = Machine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine})
models.py:
class Machine(models.Model):
machine_name = models.CharField(max_length=200)
operation_no = models.IntegerField(null=False)
def __str__(self):
return self.machine_name
upload.html:
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<select>
<option>Select Machine Name</option>
{% for machine in machines %}
<option name="machine_name">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<select>
<option>Select Operation Number</option>
{% for machine in machines %}
<option name="operation_no">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
<td>{{choiced_machine.machine_name}}</td>
<td>{{choiced_machine.operation_no}}</td>
</tr>
try this
<form action="{% url 'save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select name="machinename" id="machinename">
{% for machine in machines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select id="operationname" name="operationname">
{% for machine in machines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input type="submit" value="Save">
</form>
<tr>
{% for choice in choiced_machine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
{% endfor %}
</tr>
change your view like this.
def save_machine(request):
if request.method == "POST":
machine_name = request.POST.get('machinename', '')
operation_no = request.POST.get('operationname','')
choiced_machine = Machine.objects.filter(machine_name=machine_name, operation_no=operation_no)
machines = Machine.objects.all()
return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine})
Try to edit your form like this below.Currenlty you are not passing any value so that internal server error occurs and you are not getting any response from the server so that None error is showing
<select name="machine_name">
<option>Select Machine Name</option>
{% for machine in machines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<select name="operation_no">
<option>Select Operation Number</option>
{% for machine in machines %}
<option value="{{machine.operation_no}}">{{ machine.operation_no }}</option>
{% endfor %}
</select>

Page is opening but search is not working when i am using {% for i in kitty_list %} but in case of {% for i in kitty %} then NoReverseMatch error

In the below scenario, the page is opening but search functionality is not working when i am using {% for i in kitty_list %} in the template. However, when i am using {% for i in kitty %} then I get a NoReverseMatch error.
Url: path('kitty_view',views.kitty_view,name='kitty_view')
View: kitty_list = kitty_list.filter(status = status1)
kittys = kitty.objects.all()
ctx = {'kitty': kitty_list,'kitty_code':kittys}
return render(request, 'kitty/kitty_view.html', ctx)
This is the HTML page which is giving NoReverseMatch error when {% for i in kitty %} is used. When i am using {% for i in kitty_list %} then the page is rendering but the search button is not working.
template:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<form class="form-signin" action="{% url 'kitty_view' %}" method="get">
{% csrf_token %}
<div class="form-row">
<div class="mb-3">
<select class="custom-select center-block" name="code1" id="code1">
<option value="">Choose Kitty...</option>
{% for j in kitty_code %}
<option value="{{ j.code }}"> {{ j.code|add:' - '|add:j.name }} </option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="stat" id="stat" placeholder="Status">
<option value="">Choose Status...</option>
<option>A</option>
<option>I</option>
</select>
</div>
<div class="mb-3">
<button type="submit" class=" btn btn-info " role="button">Search</button>
</div>
</div>
</form>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Kitty Code</th>
<th scope="col">Name</th>
</tr>
</thead>
{% if kitty %}
{% for i in kitty_code %}
<tbody>
<tr>
<td>{{ i.id }} </td>
<td>{{ i.code }} </td>
<td>{{ i.name }} </td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
{% endblock %}
Inside the template file, you need to modify the below line. {% url 'kitty_view' %} to {% url '<app_name>:kitty_view' %}. If this would not work then, please give me an error in more detail.

Why is my Class-based delete view not working?

My delete view is not working and the error message is:
Page not found (404) Request Method: GET.
I am trying to delete my uploaded file based on its primary key and so far, my url is able to link me correctly based on the pk.
This is my urls.py:
path('post/<int:post_id>/lesson_delete/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'),
My views.py:
class LessonDeleteView(DeleteView):
model = Lesson
success_url = '../'
template_name = 'lesson_confirm_delete.html'
This is the html template that brings user to the delete view:
{% extends "store/base.html" %}
{% block content %}
<div id="main">
<table class="table mb-0">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Download</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for l in Lesson %}
<tr>
<td>
{% if l.file %}
{{ l.title }}
{% else %}
<h6>Not available</h6>
{% endif %}
</td>
<td>{{ l.post.author }}</td>
<td>{% if l.file %}
Download
{% else %}
<h6>Not available</h6>
{% endif %}
</td>
<td> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'lesson_delete' lesson_id=l.id %}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
This is my html template for DeleteView:
{% extends "store/base.html" %}
{% block content %}
<div class="content-section" id="main">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Delete Lesson</legend>
<h2>Are you sure you want to delete the post "{{object.title}}"?
</h2>
</fieldset>
<span style="display:inline;">
<button class="btn btn-outline-danger" type="submit">Yes, Delete!
</button>
<a class="btn btn-outline-secondary" href ="">Cancel</a>
</span>
</form>
</div>
{% endblock content %}
This is my Lesson Model:
class Lesson(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to="lesson/pdf")
date_posted = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('lesson_upload', kwargs={'pk': self.pk})
Is you template called 'lesson_confirm_delete.html'?
Also, for your success url, I have feeling you don't have a path '../'. It should the specific path you want it to go to.
(Sorry, I can't comment yet.)

Django paginator not providing content on next page

I use Django paginator to break my search results to few pages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
In my view I perform the search based on the output from the form
#login_required
def payment_range_list(request):
#import pdb; pdb.set_trace()
title = 'payment list'
#import pdb; pdb.set_trace()
if request.method == "POST":
form = PaymentRangeForm(request.POST)
#import pdb; pdb.set_trace()
if form.is_valid():
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
building = form.cleaned_data['building']
payment_list = LeasePaymentFilter(request.GET, queryset=LeasePayment.objects.filter(payment_date__range=[start_date, end_date],lease__unit__building = building ))
paginator = Paginator(payment_list, 25) # Show 25 contacts per page
page = request.GET.get('page')
try:
payment_page = paginator.page(page)
except PageNotAnInteger:
payment_page = paginator.page(1)
except EmptyPage:
payment_page = paginator.page(paginator.num_pages)
else:
payment_list = None
payment_page = None
start_date = None
end_date = None
building = None
else:
payment_list = None
payment_page = None
start_date = None
end_date = None
building = None
#form = PaymentRangeForm()
form = PaymentRangeForm(initial = {'building': 0 })
return render(request,'payment/payment_range.html', {'form':form, 'payment': payment_list,'page_payment':payment_page, 'start_date':start_date, 'end_date':end_date, 'building':building })
On the top of the page I have a form that I use for search and 2nd part is used to display the results.
{% extends "rent_base.html" %}
{% load crispy_forms_tags %}
{% block title %}
Lease List
{% endblock title %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-10 col-sm-offset-1 hid">
<h4 class="display-4">List > Payments> by Date Range </h4><div style="float:right;"> CSV for current range payments</div>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1 hid">
<form method="POST" class="form" action="" method="get">
{% csrf_token %}
{{ form|crispy}}
<br>
<button type="submit" class="btn btn-primary btn-primary">Search</button>
</form>
<br>
<b>Start date:</b> {{ start_date }} <b>End date:</b>{{ end_date }}
<br>
<table class="table table-striped">
<tr>
<th># Payment</th>
<th>Payment type</th>
<th>Amount </th>
<th>Deposit</th>
<th>Lease</th>
<th>Unit</th>
<th>Building</th>
<th>Term</th>
<th>Payment date</th>
<th>Payment method</th>
</tr>
{% for payment in page_payment %}
<tr>
<td> {{ payment.id }}</td>
<td> {{ payment.get_payment_type_display }}</td>
<td> {{ payment.amount }}</td>
<td>
{% if payment.is_deposit %}
<span class="glyphicon glyphicon-ok text-success" aria-hidden="true" ></span>
{% else %}
<span class="glyphicon glyphicon-remove text-warning" aria-hidden="true" ></span>
{% endif %}
</td>
<td> {{ payment.lease }}</td>
<td> {{ payment.lease.unit.number }}</td>
<td> {{ payment.lease.unit.building.name }}</td>
<td> {{ payment.leaseterm }}</td>
<td> {{ payment.payment_date }}</td>
<td> {{ payment.get_method_display }}</td>
</tr>
{% endfor %}
</table>
<div class="pagination">
<span class="step-links">
{% if page_payment.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ page_payment.number }} of {{ page_payment.paginator.num_pages }}.
</span>
{% if page_payment.has_next %}
next
{% endif %}
</span>
</div>
</div>
</div></div>
{% endblock content %}
My problem is that when my search returns amount of results more than 1 page and I click on next pages. The next pages are always empty.
Any feedback where my problem is?
The problem is that your serch form is POST. So when you click next button you send GET request and if request.method == "POST": part of you view is not triggered.
I suggest you to change serch form to GET:
<form method="GET" action="">
<input type="text" name="q" placeholder="Search" value="{{ request.GET.q }}">
<input type="submit" value="Search">
</form>
And change next button to this:
{% if payment.has_next %}
next
{% endif %}
This will save search value in address bar even after you move to the next page.