displaying None instead of data in the form of table - django

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>

Related

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

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>

convert string value to integer in Django template

In home.html
<div class="container">
<div class="row">
<div class="col-md-6">
<h3>Select products:</h3>
<form id="selectProduct" role="search" method="get" action="{% url 'home' %}">
<select name="parameters" data-placeholder="Choose products" class="chosen-select" multiple tabindex="4">
{% for p in productnames %}
{% if k == p %}
<option value="{{ p.productnames }}" selected> {{ p.productnames }} </option>
{% else%}
<option value="{{ p.id }}"> {{ p.productnames }} </option>
{% endif %}
{% endfor %}
</select><br/>
<label for="submit"></label><button id="submit" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<div class="row"></div><br />
<h3> Distribution of sales in the products:</h3>
</div>
</div>
{% for p in productList %}
{% for pin in productnames %}
<p>{{pin.id}} {{p}}</p>
{% if p == pin.id %}
<p>exists</p>
{% else %}
<p>not exist</p>
{% endif %}
{% endfor %}
{% endfor %}
<p>{{ productList }}</p>
in this html file 'p' always returns a string value for ex: it returns like '10' instead of 10. all i want is to convent this '10' to 10 or convert returned other p_in value to 10 to '10'.
in views.py
def productList(request):
if request.method == 'GET':
p = request.GET.get('parameters')
print(p)
#k = request.GET('parameters[]')
productnames = Products.objects.all()
context = {
'productList': p, 'productnames': productnames,
}
return render(request, 'home.html', context)
I tried to convert the values of the p in product list to integer. because it dosen't mactch the format with pin.id
You filter the queryset in the template using if-else which is not ideal. Instead you should perform this filtering in the view itself. Also your parameters is a select tag which may have multiple selected values yet you use .get('parameters') which will only give you one value instead you should use the getlist method [Django docs] of the QueryDict:
def productList(request):
if request.method == 'GET': # Do you even need to check this? You appear to only use a GET request...
p = request.GET.getlist('parameters')
productnames = Products.objects.all()
filtered_products = Products.objects.filter(pk__in=p)
context = {
'productList': p, 'productnames': productnames, 'filtered_products': filtered_products
}
return render(request, 'home.html', context)
In the template your loop would simply become:
{% for product in filtered_products %}
{{ product.productnames }}
{% endfor %}
Note: You should use a form class instead of manually making a form. See Building a form in
Django.
Also a models name should be singular hence instead of
Products you should name it Product. In general in
your code you also break various naming conventions in Python, I would
suggest you to look at PEP 8 -- Style Guide for Python
Code
In views.py
def productList(request):
if request.method == 'GET':
p = request.GET.getlist('parameters')
print(p)
#k = request.GET('parameters[]')
productnames = Products.objects.all()
context = {
'productList': p, 'productnames': productnames,
}
# --- logic later for chart ------
return render(request, 'home.html', context)
In home.html
<div class="container">
<div class="row">
<div class="col-md-6">
<h3>Select products:</h3>
<form id="selectProduct" role="search" method="get" action="{% url 'home' %}">
<select name="parameters" data-placeholder="Choose products" class="chosen-select" multiple tabindex="4">
{% for p in productnames %}
{% if k == p %}
<option value="{{ p.productnames }}" selected> {{ p.productnames }} </option>
{% else%}
<option value="{{ p.id }}"> {{ p.productnames }} </option>
{% endif %}
{% endfor %}
</select><br/>
<label for="submit"></label><button id="submit" type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<div class="row"></div><br />
<h3> Distribution of sales in the products:</h3>
</div>
</div>
{% for p in productList %}
{% for pin in productnames %}
<p>{{pin.id|stringformat:"s"}} {{p}}</p>
{% if p == pin.id|stringformat:"s" %}
<p>exists</p>
{% else %}
<p>not exist</p>
{% endif %}
{% endfor %}
{% endfor %}
<p>{{ productList }}</p>
Note {{value|stringformat:"s"}} can be used to convert integer value to string value

I want to fetch data from database using ajax and then define it in views.py to display in bar-chart

I want to fetch the data from database. I am using Ajax and then I want to define it in views.py to extract the data and display it in view(webpage) using Django. How may I approach in order to bring "be_total" the data from the database and then display the values of "be_total" in the form of bar chart on my webpage?
Can anyone please help me ?
My codes are:
index.html:
<form class="form-row" method="post" >
{% csrf_token %}
<div class="form-group col-md-2" >
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m1">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m2">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m3">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m4">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control select2" >
<option>Select M Head</option>
{% for major in majors %}
<option value="{{ major.pk }}" id="m5">{{ major.pk }}: {{ major.description }}</option>
{% endfor %}
</select>
</div>
<div class="form-group col-md-2">
<button type="button" onclick="submitData()">Submit</button>
</div>
</form>
````
````
<script type="text/javascript">
function submit(){
// Get answer from the input element
var dt = document.getElementById("m1").value;
var dtt = document.getElementById("m2").value;
var dttt = document.getElementById("m3").value;
var dtttt = document.getElementById("m4").value;
var dttttt = document.getElementById("m5").value;
// add the url over here where you want to submit form .
var url = 'home';
$.ajax({
url: url,
data: {
'm1': dt,
'm2': dtt,
'm3': dttt,
'm4': dtttt,
'm5': dttttt,
},
dataType: 'JSON',
success: function(data){
// show an alert message when form is submitted and it gets a response from the view where result is provided and if url is provided then redirect the user to that url.
alert(data.result);
if (data.url){
window.open(data.url, '_self');
}
}
});
}
</script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
**views.py:**
def home(request):
majors = Major.objects.filter(percentages__isnull=False).distinct().order_by("pk")
if request.method == 'POST':
form = request.POST.get('be_nextyr_total')
line_chart = pygal.Line(width=1500)
line_chart.title = 'Budget Estimation'
context = {
"chart": line_chart.render_data_uri(),
'majors': majors
}
return render(request, "website/index.html" , context )
you have to specify type in your ajax code like this
type:'POST'

Use cycle for value in template

How to access "value" in if condition? Or it's not possible in django tamplates?
Here is my example what I would like to be possible in django, but it doesn't work.
So I have problem with this row "{% if field.data == value %}" How to pass "value" from "for cycle" to if condition?
What is best solution for this?
template file
{% for field in form1 %}
<div class="row pad-col i-l">
{{ field.errors }}
<div class="col-sm-5 text-right">
<label for="{{ field.id_for_label }}">
{{ field.label }}
</label>
</div>
{% if field|field_type == 'Select' %}
<div class="col-sm-7 a-select">
<div class="a-m">
<select class="selectpicker add-i" id="{{ field.id_for_label }}" data-live-search="true" name="{{ field.name }}" tabindex="-98">
{% for value, key in field.field.choices %}
{% if field.data == value %}
<option value="{{ value }}" selected>{{ key }}</option>
{% else %}
<option value="{{ value }}">{{ key }}</option>
{% endif %}
{% endfor %}
</select>
</div>
</div>
{% else %}
<div class="col-sm-7">
{{ field }}
</div>
{% endif %}
</div>
{% endfor %}
views.py file
def add_item(request):
form1 = AddForm()
if request.method == 'POST':
form1 = AddForm(data=request.POST)
if form1.is_valid():
form1.save()
return HttpResponse('good')
return render(request, 'add_item.html', {'form1': form1})
Sorry guys. I just solved by myself. It was really stupid idea to customize that way forms when you can just add "widget=forms.Select(attrs={'class': 'selectpicker add-i', 'data-live-search': 'true'})" to your form field in forms.py file and all validation is working.
And than instead of this:
<select class="selectpicker add-i" id="{{ field.id_for_label }}" data-live-search="true" name="{{ field.name }}" tabindex="-98">
{% for value, key in field.field.choices %}
{% if field.data == value %}
<option value="{{ value }}" selected>{{ key }}</option>
{% else %}
<option value="{{ value }}">{{ key }}</option>
{% endif %}
{% endfor %}
</select>
you just write this:
{{ field }}
I think you should assign just one controlling var to the iteration, and then call the fields on it (assuming "value" and "key" are part of the field choices), like this:
{% for vfield in field.field.choices %}
{% if field.data == value %}
<option value="{{ vfield.value }}" selected>{{ vfield.key }}</option>
{% else %}
<option value="{{ vfield.value }}">{{ vfield.key }}</option>
{% endif %}
{% endfor %}

How do I iterate over the options of a SelectField in a template?

I have a select field in the form and now I need to iterate over options in this field.
{{ form.myselect }} gives me this:
<select name="myselect" id="id_myselect">
<option value="" selected="selected">---------</option>
<option value="2">Item 1</option>
<option value="3">Item 2</option>
...
</select>
Now I need to add some attributes to the options and because of that what I need is:
<select name="myselect" id="id_myselect">
{% for x in form.myselect %}
<option value="{{ x.id }}">{{ x.name }}</option>
{% endfor %}
</select>
but there is an error:
Caught TypeError while rendering: 'BoundField' object is not iterable
I tried form.myselect.all, form.myselect.option_set but it gives nothing
I've been struggling with this problem today and found the solution. Yes, you can iterate over options of the select tag directly in template. Here's how to do it in template:
<select id="id_customer" name="customer">
{% for x, y in form.fields.customer.choices %}
<option value="{{ x }}"{% if form.fields.customer.value == x %} selected{% endif %}>{{ y }}</option>
{% endfor %}
</select>
In this case I have a customer field in the form which has choices set up as follows:
class SomeForm(forms.Form):
customer = forms.ChoiceField(label=u'Customer')
def __init__(self, *args, **kwargs):
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['customer'].choices = [(e.id, e.customer) for e in Customers.objects.all()]
Got it to work with:
<select name="myselect" class="i-can-add-my-own-attrs-now" id="id_myselect">
{% for id, name in form.myselect.field.choices %}
<option value="{{ id }}">{{ name }}</option>
{% endfor %}
</select>
BUT REALLY, a better way to do this is with django-widget-tweaks:
{% load widget_tweaks %}
{{ form.myselect|add_class:"i-can-haz-custom-classes-easily" }}
Doing it with django-widget-tweaks will also set the default 'selected="selected"' for you, which is super nice!
I do this way:
<select id="id_construction_type" name="construction_type" class="form-control input-md">
{% for value, key in form_urban.fields.construction_type.choices %}
<option value="{{ value }}"{% if form_urban.initial.construction_type == value %} selected {% endif %}>
{{ key }}
</option>
{% endfor %}
</select>
This is a cleaner solution, you can set the attributes using a custom Widget. This way you don't have to render the field manually:
class CustomSelectWidget(forms.Select):
def create_option(self, name, value, *args, **kwargs):
option = super().create_option(name, value, *args, **kwargs)
if value:
instance = self.choices.queryset.get(pk=value) # get instance
option['attrs']['custom_attr'] = instance.field_name # set option attribute
return option
class SomeForm(forms.ModelForm):
some_field = forms.ModelChoiceField(
queryset=SomeModel.objects.all(),
widget=CustomSelectWidget
)
With radio buttons in your template use.
<table>
{% for x,y in form.fields.Customer.choices %}
<tr>
<td><input id="id_Customer_{{x}}" {% if form.fields.Customer.value == x %}checked="checked"{% endif %} name="Customer" type="radio" value="{{x}}" /></td>
<td>{{ y }}</td>
</tr>
{% endfor %}
</table>