if i'm Create Dynamically table using jquery this is working
This is my .html file code.
<!DOCTYPE html>
<html>
<head>
<title>test page</title>
<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity=
"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous">
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js">
</script>
<script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">
</script>
<script>
$(document).ready(function () {
// Denotes total number of rows
var rowIdx = 0;
// jQuery button click event to add a row
$('#addBtn').on('click', function () {
// Adding a row inside the tbody.
$('#tbody').append(`<tr id="R${++rowIdx}">
<td class="row-index text-center">
<p>${rowIdx}</p>
</td>
<td class="row-index text-center">
<input type="text" name="organization">
</td>
<td class="row-index text-center">
<input type="text" name="designation">
</td>
<td class="row-index text-center">
<input type="date" name="date_from">
</td>
<td class="row-index text-center">
<input type="date" name="date_to">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button">Remove</button>
</td>
</tr>`);
});
// jQuery button click event to remove a row.
$('#tbody').on('click', '.remove', function () {
// Getting all the rows next to the row
// containing the clicked button
var child = $(this).closest('tr').nextAll();
// Iterating across all the rows
// obtained to change the index
child.each(function () {
// Getting <tr> id.
var id = $(this).attr('id');
// Getting the <p> inside the .row-index class.
var idx = $(this).children('.row-index').children('p');
// Gets the row number from <tr> id.
var dig = parseInt(id.substring(1));
// Modifying row index.
idx.html(`Row ${dig - 1}`);
// Modifying row id.
$(this).attr('id', `R${dig - 1}`);
});
// Removing the current row.
$(this).closest('tr').remove();
// Decreasing total number of rows by 1.
rowIdx--;
});
});
</script>
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<form method="post">
{% csrf_token %}
<div class="row pt-3">
<div class="col-md-6">
<input type="text" class="form-control" placeholder="first name" name="first_name">
</div>
<div class="col-md-6 " >
<input type="text" class="form-control" placeholder="last name" name="last_name">
</div>
</div>
<div class="row pt-5">
<div class="col-md-4">
<input type="email" class="form-control" placeholder="Email Address" name="email_id">
</div>
<div class="col-md-4">
<input type="text" class="form-control" placeholder="Mobile No" name="mobile_no">
</div>
<div class="col-md-4">
<input type="date" class="form-control" name="dob">
</div>
</div>
<h3>Qualification</h3>
<select id="inputState" class="form-select" name="qualification">
<option>Choose...</option>
<option>B.A</option>
<option>B.tech.</option>
<option>BBA</option>
<option>BCA</option>
<option>M.tech</option>
<option>MBA</option>
<option>MCA</option>
<option>Other</option>
</select>
<div class="pt-3">
<table class="table table-bordered">
<thead>
<tr>
<th>S.N</th>
<th class="text-center">Organization Name </th>
<th class="text-center">Designation</th>
<th class="text-center">From </th>
<th class="text-center">To</th>
<th class="text-center">Remove Row</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<button class="btn btn-md btn-primary"
id="addBtn" type="button">
Add experince
</button>
</div>
<div class="col-12 pt-3">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</form>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
-->
</body>
</html>
This is my Views.py file code
from django.shortcuts import render
from .models import *
Create your views here.
def home(request):
if request.method == 'POST':
detail(first_name = request.POST['first_name'],
last_name = request.POST['last_name'],
email_id = request.POST['email_id'],
mobile_no = request.POST['mobile_no'],
dob = request.POST['dob'],
qualification = request.POST['qualification'],
organization = request.POST['organization'],
designation = request.POST['designation'],
date_from = request.POST['date_from'],
date_to = request.POST['date_to']).save()
return render(request,"home.html")
This is model.py files code..
from django.db import models
# Create your models here.
class detail(models.Model):
first_name = models.CharField(max_length=96)
last_name = models.CharField(max_length=96)
email_id = models.CharField(max_length=96)
mobile_no = models.CharField(max_length=96)
dob = models.CharField(max_length=96)
qualification = models.CharField(max_length=96)
experince = models.CharField(max_length=96)
organization = models.CharField(max_length=96)
designation = models.CharField(max_length=96)
date_from = models.CharField(max_length=96)
date_to = models.CharField(max_length=96)
def __str__(self):
return self.first_name
I am working on a project which requires me to create a table of every workng company experince.The columns in the table are same for every experince.
if i'm submit the data on database. Than save only last table row data if i'm create one or more rows....
That happened because the values are sent always to the same experince Field so django will alwasy take the latest value you entered. Your detail model is the problem.
You must have a seperate model for Experince and experience field with relation on the detail model. then you can store any number of
experince you want
Related
While trying to submit input type = range i'm getting "Bad request error".
HTML:
{% extends "base.html" %} {% block content %} <head>
<link rel="stylesheet" href="css/style.css" />
</head>
<div class="search-bar">
<div class="rt-container">
<form method="post" action="#">
<div class="col-rt-12">
<div class="Scriptcontent">
<!-- Range Slider HTML -->
<div slider id="slider-distance">
<div>
<div inverse-left style="width: 70%"></div>
<div inverse-right style="width: 70%"></div>
<div range style="left: 30%; right: 40%"></div>
<span thumb style="left: 30%"></span>
<span thumb style="left: 60%"></span>
<div sign style="left: 30%">
<span id="value">0</span>
</div>
<div sign style="left: 60%">
<span id="value">100</span>
</div>
</div>
<input name="max" type="range" tabindex="0" value="30" max="100" min="0" step="1" oninput="
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
var children = this.parentNode.childNodes[1].childNodes;
children[1].style.width=value+'%';
children[5].style.left=value+'%';
children[7].style.left=value+'%';children[11].style.left=value+'%';
children[11].childNodes[1].innerHTML=this.value;" />
<input name="min" type="range" tabindex="0" value="60" max="100" min="0" step="1" oninput="
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
var children = this.parentNode.childNodes[1].childNodes;
children[3].style.width=(100-value)+'%';
children[5].style.right=(100-value)+'%';
children[9].style.left=value+'%';children[13].style.left=value+'%';
children[13].childNodes[1].innerHTML=this.value;" />
<input id="search" type="submit" value="SEARCH" href="#"></input>
</div>
</form>
</div>
</div>
</div>
<form action="/lobbies" method="POST">
<input type="checkbox" name="IsVisible" value="0" default="0">Private?</input>
<input type="text" name="LobbyValue" placeholder="Value" href="#" required></input>
<input type="submit" value="CREATE" href="#"></input>
</form>
</div>
<div class="container"> {% for lobby in data%} <div class="lobby-item">
<div class="lobby-coins">
<img src="static/StashedCoins.png" alt="coin" width="32px" height="32px" /> {% print lobby['GameValue']%}
</div>
<div class="lobby-photo">
<a href="/Player/{{lobby['PlayerOneID']}}">
<img src=https://robohash.org/{{lobby['CreatorName']}} alt="coin" width="110px" height="110px" />
</a>
</div>
<div class="lobby-join">
Join
</div>
</div>
{%endfor%}
</div>
{% endblock %}
Flask:
#app.route("/lobbies", methods=["GET", "POST"])
def lobbies():
if "username" in session:
coins = requests.get(API_URL + "/GetUserBalance/" + str(session["id"])).json()[
"balance"
]
ProfilePicture = "https://robohash.org/" + str(session["username"])
color = str(session["color"])
PlayerID = session["PlayerID"]
if request.method == "POST":
LobbyValue = request.form['LobbyValue']
if "IsVisible" in request.form:
response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "IsVisible": 0, "LobbyValue": LobbyValue}).json()
else:
response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "LobbyValue": LobbyValue}).json()
LobbyID = response['LobbyID']
return redirect(url_for('lobby',LobbyID=LobbyID))
data = requests.get(API_URL + "/GetLobbies", params={"PlayerID": PlayerID})
return render_template(
"lobbies.html",
coins=coins,
ProfilePicture=ProfilePicture,
color=color,
data=data.json(),
)
else:
return redirect(url_for("login"))
I dont understand what im doing wrong here.
I want to give user a slider with two handlers like this:
So they can filter the lobbies within the price range set in slider. I need in this example number 0 and 69 to be send to my flask app so i can then display lobbies within the price range.
let say these are the inputs of user, in my view it's well validated form.is_valid().
item code | description | unit | quantity
---------------------------------------------------------------
#itemInput1 | #descriptionInput1 | #unitInput1 | #quantityInput1
#itemInput2 | #descriptionInput2 | #unitInput2 | #quantityInput2
#itemInput3 | #descriptionInput3 | #unitInput3 | #quantityInput3
reqeust.POST.getlist('description')
return a list -> ['#descriptionInput1','#descriptionInput2','#descriptionInput3']
How can i save all the cells that the user enter to my MaterialIndent model??
just like in myview i could only save the last item only !!
# models
class MaterialIndent(models.Model):
material_indent_id = models.AutoField(primary_key=True)
date_request = models.DateTimeField(auto_now_add=True)
local_code = models.CharField(max_length=10, default='Local')
quotation = models.FileField(upload_to='files/', null=True, blank=True)
description = models.CharField(max_length=200)
unit = models.CharField(max_length=100)
quantity_requested = models.DecimalField(max_digits=12, decimal_places=2)
quantity_remained = models.DecimalField(max_digits=12, decimal_places=2, null=True)
request_for = models.CharField(max_length=50)
requester = models.ForeignKey(User, on_delete=models.CASCADE)
priority = models.CharField(max_length=100)
status = models.CharField(max_length=50, default='Store Checking')
def __str__(self):
return str(self.material_indent_id)
# form
class MaterialIndentForm(ModelForm):
class Meta:
model = MaterialIndent
fields = ['local_code', 'description', 'unit', 'quantity_requested', 'request_for', 'priority','quotation']
# views
def test(request):
available_stock = SparePartsStock.objects.filter(quantity__gte=0).values_list('local_code', flat=True)
if request.method == 'POST':
form = MaterialIndentForm(request.POST, request.FILES)
if form.is_valid():
length = len(request.POST.getlist('local_code'))
post = form.save(commit=False)
for r in range(length):
local_code = request.POST.getlist('local_code')[r]
description = request.POST.getlist('description')[r]
unit = request.POST.getlist('unit')[r]
quantity_requested = request.POST.getlist('quantity_requested')[r]
post.local_code = local_code
post.description = description
post.unit = unit
post.quantity_requested = quantity_requested
post.requester = request.user
post.quantity_remained = post.quantity_requested
post.status = 'Store Checking'
post.save()
print('form is valid')
else:
print(form.errors)
else:
sparestock = SparePartsStock.objects.all()
form = MaterialIndentForm()
context = {'form': form, 'stock':available_stock, 'table': sparestock}
return render(request, 'copy.html', {})
# template
{% extends 'inventory.html' %}
{% load static %}
{% load crispy_forms_filters %}
{% block title %}
SG
{% endblock %}
{% block head %}
<style>
.container{
padding: 100px;
}
#priority_label{
margin-left: 15px;
}
#submit_button {
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
background-color: #555555;/* Black */
}
.btn {
background-color: DodgerBlue;
border: none;
color: white;
padding: 12px 16px;
font-size: 16px;
cursor: pointer;
}
/* Darker background on mouse-over */
.btn:hover {
background-color: RoyalBlue;
}
#rowAdder{
margin-left: 15px;
right: 10px;
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css">
<script src="{% static 'js/jQuery.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
{% endblock %}
{% block content %}
<div class="container">
<h2 style="">Material Indent</h2>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="card">
<div class="card-header">
<label id="priority_label" for="rate">Priority</label><br>
<div class="rate">
<input type="radio" id="star5" name="priority" value="High" required/>
<label for="star5" title="High">High</label>
<input type="radio" id="star4" name="priority" value="Medium" required/>
<label for="star4" title="Medium">Medium</label>
<input type="radio" id="star3" name="priority" value="Low" required/>
<label for="star3" title="Low">Low</label>
</div>
<input name="request_for" type="text" class="form-control m-input" placeholder="Requested For" required><br>
<label for="quotation">Quotation: </label>
<input type="file" name="quotation" placeholder="Quotation">
</div>
<div class="card-body">
<div class="">
<div class="col-lg-12">
<div id="row">
<div class="input-group m-3">
<div class="input-group-prepend">
<button class="btn btn-danger"
id="DeleteRow" type="button">
<i class="bi bi-trash"></i>
-
</button>
</div>
<input id="local_code0" name="local_code0" type="text" class="form-control m-input" placeholder="Local Code" required list="localList">
<datalist id="localList">
{% for item in stock %}
<option value={{ item }}>
{% endfor %}
</datalist>
<input name="description0" type="text" class="form-control m-input" placeholder="Description">
<input name="unit0" type="text" class="form-control m-input" placeholder="Unit">
<input name="quantity0" type="text" class="form-control m-input" placeholder="Quantity">
</div>
</div>
<div id="newinput"></div>
<button id="rowAdder" type="button"
class="btn btn-dark">
<span class="bi bi-plus-square-dotted" id="plus_sign">
</span> +
</button>
<input type="hidden" name="length" id="length">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="button button5" id="submit_button">Submit</button>
</div>
</form>
</div>
<script type="text/javascript" >
let count = Number(1)
document.getElementById('length').value = 0
console.log(document.getElementById('length').value)
$("#rowAdder").click(function () {
document.getElementById('length').value = count
newRowAdd =
'<div id="row"> <div class="input-group m-3">' +
'<div class="input-group-prepend">' +
'<button class="btn btn-danger" id="DeleteRow" type="button">' +
'<i class="bi bi-trash"></i> - </button> </div>' +
'<input name=local_code' + count +' type="text" class="form-control m-input" placeholder="Local Code" list="localList" required>'+
'<input name=description'+count+ ' type="text" class="form-control m-input" placeholder="Description" required>'+
'<input name=unit'+count+ ' type="text" class="form-control m-input" placeholder="Unit" required>'+
'<input name=quantity'+count+ ' type="text" class="form-control m-input" placeholder="Quantity" required> </div> </div>'
;
$('#newinput').append(newRowAdd);
count ++
});
$("body").on("click", "#DeleteRow", function () {
$(this).parents("#row").remove();
count --
})
</script>
<script src="{% static 'js/material_indent_autofill.js' %}"></script>
{% include 'spare_parts_table.html' %}
{% endblock %}
I'm following this tutorial https://studygyaan.com/django/how-to-execute-crud-using-django-ajax-and-json
I'm trying to update my database with the CreateCrudUser class, but when I click submit the data goes to the end of the url and it doesn't update the databse. If i add the word "create" in front of the JSON it puts in the url it will update the database.
View.py
class CrudView(ListView):
model = models.CrudUser
template_name = 'newsfeed/crud.html'
context_object_name = 'users'
class CreateCrudUser(View):
def get(self, request):
name1 = request.GET.get('name', None)
address1 = request.GET.get('address', None)
age1 = request.GET.get('age', None)
obj = models.CrudUser.objects.create(
name = name1,
address = address1,
age = age1
)
user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age}
data = {
'user': user
}
return JsonResponse(data)
url.py
from django.urls import path, include
from social_method.apps.newsfeed import views
app_name = "newsfeed"
urlpatterns = [
#path('observation-feed/', views.ObservationFeed, name='observation-feed'),
path('', views.ObservationFeed, name='observation-feed'),
path('observation/<str:pk>/', views.ObservationThread, name='observation'),
path('new-social-method/<str:pk>/', views.SocialMethod, name='new-social-method'),
path('crud/', views.CrudView.as_view(), name='crud_ajax'),
path('ajax/crud/create/', views.CreateCrudUser.as_view(), name='crud_ajax_create'),
]
models.py
class CrudUser(models.Model):
name = models.CharField(max_length=30, blank=True)
address = models.CharField(max_length=100, blank=True)
age = models.IntegerField(blank=True, null=True)
html
<div class="container">
<h1>Django Ajax CRUD</h1>
<h2>{% url "newsfeed:crud_ajax_create" %}</h2>
<div class="row">
<div class="col-md-4 ">
<h3>ADD USER</h3>
<form id="addUser" action="">
<div class="form-group">
<input class="form-control" type="text" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<input class="form-control" type="text" name="address" placeholder="Address" required>
</div>
<div class="form-group">
<input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age" required>
</div>
<button class="btn btn-primary form-control" type="submit">SUBMIT</button>
</form>
</div>
<div class="col-md-8">
<h3>USERS</h3>
<table id="userTable" class="table table-striped">
<tr>
<th>Name</th>
<th>Address</th>
<th colspan="3">Age</th>
</tr>
{% if users %}
{% for user in users %}
<tr id="user-{{user.id}}">
<td class="userName userData" name="name">{{user.name}}</td>
<td class="userAddress userData" name="address">{{user.address}}</td>
<td class="userAge userData" name="age">{{user.age}}</td>
<td align="center">
<button class="btn btn-success form-control" onClick="editUser({{user.id}})" data-toggle="modal" data-target="#myModal")">EDIT</button>
</td>
<td align="center">
<button class="btn btn-danger form-control" onClick="deleteUser({{user.id}})">DELETE</button>
</td>
</tr>
{% endfor %}
{% else %}
No Users
{% endif %}
</table>
</div>
</div>
</div>
<!-- Modal -->
<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">Update User</h4>
</div>
<form id="updateUser" action="">
<div class="modal-body">
<input class="form-control" id="form-id" type="hidden" name="formId"/>
<label for="name">Name</label>
<input class="form-control" id="form-name" type="text" name="formName"/>
<label for="address">Address</label>
<input class="form-control" id="form-address" type="text" name="formAddress"/>
<label for="age">Age</label>
<input class="form-control" id="form-age" type="number" name="formAge" min=10 max=100/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
// Create Django Ajax Call
$("form#addUser").submit(function() {
var nameInput = $('input[name="name"]').val().trim();
var addressInput = $('input[name="address"]').val().trim();
var ageInput = $('input[name="age"]').val().trim();
if (nameInput && addressInput && ageInput) {
// Create Ajax Call
$.ajax({
url: '{% url "newsfeed:crud_ajax_create" %}',
data: {
'name': nameInput,
'address': addressInput,
'age': ageInput
},
dataType: 'json',
success: function (data) {
if (data.user) {
appendToUsrTable(data.user);
}
}
});
} else {
alert("All fields must have a valid value.");
}
$('form#addUser').trigger("reset");
return false;
});
function appendToUsrTable(user) {
$("#userTable > tbody:last-child").append(`
<tr id="user-${user.id}">
<td class="userName" name="name">${user.name}</td>
'<td class="userAddress" name="address">${user.address}</td>
'<td class="userAge" name="age">${user.age}</td>
'<td align="center">
<button class="btn btn-success form-control" onClick="editUser(${user.id})" data-toggle="modal" data-target="#myModal")">EDIT</button>
</td>
<td align="center">
<button class="btn btn-danger form-control" onClick="deleteUser(${user.id})">DELETE</button>
</td>
</tr>
`);
}
</script>
I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes .
I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes.
My code is as:
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
views.py
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from user.models import *
def size(request):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
else:
size_show = Size.objects.all()
# start paginator logic
paginator = Paginator(size_show, 3)
page = request.GET.get('page')
try:
size_show = paginator.page(page)
except PageNotAnInteger:
size_show = paginator.page(1)
except EmptyPage:
size_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/size.html', {'size_show': size_show})
def size_edit(request, id):
size_edit = Size.objects.filter(size_id=id)
return render(request, 'admin1/size.html', {'size_edit': size_edit})
def size_edit_update(request, id):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(size_id=id, prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
def size_delete(request, id):
size_deletee = Size.objects.filter(size_id=id)
size_deletee.delete()
return redirect('/admin1/productSize')
As I created add, update, delete functionality for Size I am going to do it same with color and Papaer choice.
size.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size{% endblock %}
{% block main %}
<h1>
<center>Size</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size
</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 Product Size</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-product-size'%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
<br>
<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>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
{% if size_show %}
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Product Id</th>
<th>Product Size</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in size_show %}
<tr>
<td>{{x.size_id}}</td>
<td>{{x.prod_size}}</td>
<td><a href="/admin1/size_edit/{{x.size_id}} "
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="/admin1/size_delete/{{x.size_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 size_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in size_show.paginator.page_range %}
{% if size_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 size_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if size_edit %}
{% for x in size_edit %}
<form action="/admin1/size_data_update/{{x.size_id}}" method="POST">
{% csrf_token %}
<label>Size Name:</label>
<input type="text" name="prod_size" value="{{x.prod_size}}" class="form-control w-50"><br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
</form>
{% endfor %}
{% endif %}
</div>
</div>
</div>
{% endblock %}
For performing oertions of views.py I have created size.html .Nut there around 10 to 12 product attributes ,and for that attributes I don't want to create seprate html pages.
I want to do all the operations for all the attributes in single html page. Is it possible?
Means according to the atrribut type request the page data should change dynamically, I do not have to create seprate template pages for each attribute.
You need to make the form in your views, not the Templates, I'm not sure if this is best practise but it's the only way I see you can do this, (using Class-Based Views would simplify this process a lot) but if you want to stick to functions, this is what you do.
Let's take an input line:
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
Let's use Django's tags and turn it into this:
<label>{{form.display_name}}:</label>
<input type="text" name="{{form.name}}" class="form-control w-50">
The class will probably be the same but you could extend the same functionality to the class or type fields.
In the backend, you want to make a list of all the elements you want to show, with nested dictionaries:
forms = [ # Each form
[ # Each field within the form, this way, you can have a different amount each time
{'display_name': 'Product Size', # label Display name
'name': 'prod_size'}, # name tag value
{'display_name': "it's value", # This is a different field
'name': 'just an example'}
],
]
Then you can do a for loop in the templates:
{% for form in forms %}
{$ for field in form %}
<label>{{field.display_name}}:</label>
<input type="text" name="{{field.name}}" class="form-control w-50">
I'm not exactly sure what you're trying to do in your code, so I didn't make this example too specific, but hopefully, it will give you inspiration to get you on the right track, if you need more help, just ask
I create a view which add data from a file. The function will returns two dictionaries, one with data to be saved and one with data on errors.
I would like to send back to template errors only if there is errors.
Thanks for helping.
My actual code send me back an error: Reverse for 'importXLS.views.import_choices' with arguments '(['miss.....
urls.py
path('import_choices/', views.import_choices, name='import-choices'),
# views function
url(r'^data_upload_coa$', views.data_upload_coa, name='data_upload_coa'),
view.py
def data_upload_coa(request): # importing chart of account
if request.method == 'POST':
# Get the form data from the request.
company = request.POST.get('company')
excel_file = {}
excel_file = request.FILES["excel_file"]
# return two dictionaries from coa
accounts, errors = parse_coa(excel_file)
# Add accounts to chart of accounts table
for account in accounts:
# Create a new record with the data if does not exists before.
upload_data = ChartOfAccount.objects.get_or_create(
field_account=account['field_account'],
field_account_libaccount=account['field_account_libaccount'],
field_type=account['field_type'],
field_subtype=account['field_subtype'],
)
# company=company, TO BE ADDED WHEN DEVELOPPING MULTI FIRMS DATA
# Add save success message
messages.success(request, 'Chart of accounts updated')
test = len(errors)
if test == 0:
return redirect(import_choices)
else:
return redirect(import_choices, errors)
else:
# error message
messages.info(request, 'Uploading error')
return redirect(import_choices)
import_choice.html
{% extends 'layouts/base.html' %}
{% load bootstrap3 %}
{% block title %}Import Choices{% endblock %}
{% block heading %}<h3 class="page-header-center">File to import</h3>
{% endblock %}
<hr>
<hr>
{% block page %}
<script> // logic for validation of file
var _validFileExtensions = [".xlsx", ".xls"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
</script>
<script> // Recupere le path du fichier
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
</script>
</br>
</br>
<div class="container">
<div class="panel-heading">
<h4 class="panel-title col-md-6">Please choose a type of file to import:</h4>
</div>
</br>
</br>
<!----------------Accordeon ----------------->
<div class="panel-group col-md-6" id="Choices" >
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" data-target="#Choice-COA" data-toggle="collapse" data-parent="#Choices">Chart of Accounts</h3>
</div>
<!--accordeon part 1 -->
<div class="panel-collapse collapse" id="Choice-COA">
<div class="panel-body">
<div class="row col-md-4" >
<form method="POST" action="{% url 'data_upload_coa' %}" method="post" id="fileupload" name="fileupload" enctype="multipart/form-data" data-ajax="false" onsubmit="return Validate(this);">
{% csrf_token %}
<table class="table">
<tr>
<td>
<input type="text" placeholder="Enter Company Name " name="company" id="company" required>
</td>
</br>
<td>
<input type="file" title="Upload excel file" name="excel_file" id="myfile" required="required">
</br>
<button type="submit" class="btn btn-primary btn-sm pull-right">Upload</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</br>
<!--accordeon part 2 -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" data-target="#import-bv" data-toggle="collapse" data-parent="#Choices">Balance of verification</h3>
</div>
<div class="panel-collapse collapse" id="import-bv">
<div class="panel-body">
<p>To be complete Balance of verification
test</p>
</div>
</div>
</div>
</div>
Result should be:
If errors dictionary is empty go back to import_choice.html
If not: go back to import_choice.html with list in errors shown
in my views. I modified:
if test == 0:
return redirect(import_choices)
else:
return render(request, 'imports/import_choices.html', {"errors": errors})
and in my html file at the end:
{% if errors %}
<div class="panel-body">
<table class="table table-bordered table-hover table-striped col-md-3">
<thead class="thead-dark">
<tr class="text-center">
<th>Accounts with error</th>
</tr>
</thead>
<tbody>
{% for err in errors %}
<tr>
<td scope="row" class="col-md-3">{{ err|capfirst }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}