How to stop duplicate entry into django model - django-forms

I want to stop duplicate entry into form field. If I enter the same data which is already stored into database then it shows an error message or it won't stored. Please Help me guys. I am new in Django.
Form.html File
<form class="well form-horizontal" method="post" action="{% url 'manager_add' %}">
{% csrf_token %}
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label">Manager Name</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span><input id="fullName" name="mname" placeholder="Full Name" class="form-control" required="true" value="" type="text"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Select Department</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon" style="max-width: 100%;"><i class="glyphicon glyphicon-list"></i></span>
<select class="selectpicker form-control" name="dprtmnt">
<option>Department 1</option>
<option>Department 2</option>
<option>Department 3</option>
<option>Department 4</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Email</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span><input id="email" name="email" placeholder="Email" class="form-control" required="true" value="" type="text"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Contact</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span><input id="phoneNumber" name="phone" placeholder="Phone Number" class="form-control" required="true" value="" type="text"></div>
</div>
</div>
<button>Submit</button>
</fieldset>
</form>
Model.py File
class Manager(models.Model):
mname = models.CharField(max_length=20)
dprtmnt = models.CharField(max_length=10)
email = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
def __str__(self):
return self.mname
View.py File
def manager_add(request):
print("Form is submitted successfully!")
mname = request.POST.get("mname", False)
dprtmnt = request.POST.get("dprtmnt", False)
email = request.POST.get("email", False)
phone = request.POST.get("phone", False)
ManagerAdd = Manager(mname = mname, dprtmnt = dprtmnt, email = email, phone = phone, is_active=False)
ManagerAdd.save()
return render(request,'manageradd.html')

You can use Manager.objects.get_or_create(), see this part of the doc.
You can also simple check if an entry already exists in your database:
try:
Manager.objects.get(mname = mname, dprtmnt = dprtmnt, email = email, phone = phone)
# Do things if manager exists
except:
# Create your new manager

Related

Method Illuminate\Database\Eloquent\Collection::save does not exist

i have a problem when updating the database
error: Method Illuminate\Database\Eloquent\Collection::save does not exist.
controller:
public function actualizar(Request $request){
$nuevoIngreso = \App\Models\Servicio::all();
$nuevoIngreso->costo = $request->costo;
$nuevoIngreso->duracion = $request->duracion;
$nuevoIngreso->mantenimiento = $request->mantenimiento;
$nuevoIngreso->save();
return redirect('servicios')->with('mensaje', 'Ficha Actualizada.');
}
blade.php
<form method="POST" action="{{ route('actualizar') }}">
{{method_field('PUT')}}
#csrf
#foreach ($servicios as $costo)
<h1 class="text-center text-primary"> {{$costo->tipo}} </h1>
<div class="form-group row">
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Costo</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->costo}}">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">DuraciĆ³n</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->duracion}}" id="example-text-input">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Mantenimiento</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->mantenimiento}}" id="example-text-input">
</div>
</div>
<hr>
#endforeach
<button type="submit" class="btn btn-success float-right" float-rightdata-toggle="sweet-alert" data-sweet-alert="success">SAVE</button>
</form>
help please
Error is clear.you are calling static method all().So it should be
$nuevoIngreso =new \App\Models\Servicio();
$nuevoIngreso->costo = $request->costo;
$nuevoIngreso->duracion = $request->duracion;
$nuevoIngreso->mantenimiento = $request->mantenimiento;
$nuevoIngreso->save();
So if you are thinking to update particular record then find by id or any column
$nuevoIngreso =new \App\Models\Servicio::find($id);
$nuevoIngreso->costo = $request->costo;
$nuevoIngreso->duracion = $request->duracion;
$nuevoIngreso->mantenimiento = $request->mantenimiento;
$nuevoIngreso->save();
Updated
<form method="POST" action="{{ route('actualizar') }}">
{{method_field('PUT')}}
#csrf
#foreach ($servicios as $key=>$costo)
<h1 class="text-center text-primary"> {{$costo->tipo}} </h1>
<input class="form-control" type="hidden" value="{{$costo->id}}" name="service[{{$key}}][id]">
<div class="form-group row">
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Costo</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->costo}}" name="service[{{$key}}][costo]">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">DuraciĆ³n</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->duracion}}" id="example-text-input" name="service[{{$key}}][duracion]">
</div>
<label for="example-text-input" class="col-md-2 col-form-label form-control-label">Mantenimiento</label>
<div class="col-md-10">
<input class="form-control" type="text" value="{{$costo->mantenimiento}}" id="example-text-input" name="service[{{$key}}][mantenimiento]">
</div>
</div>
<hr>
#endforeach
<button type="submit" class="btn btn-success float-right" float-rightdata-toggle="sweet-alert" data-sweet-alert="success">SAVE</button>
</form>
Then in controller
foreach($request->service as $key=>$value){
$nuevoIngreso =new \App\Models\Servicio::find($value['id']);
if($nuevoIngreso){
$nuevoIngreso->costo = $value['costo'];
$nuevoIngreso->duracion = $value['duracion'];
$nuevoIngreso->mantenimiento = $value['mantenimiento'];
$nuevoIngreso->save();
}
}

fetch datas from database based on selected data dropdown using laravel 8

hai everyone i want to fetch data (affected device name, device intended use, class of device) from database based on my selected dropdown (mda registration num),i get the registration numb er from database but i don't how to fetch other related datas based on registration num.How i can gets datas.Here my controller n create.blade.php,pls help me
create.blade.php
<div class="form-group row">
<label for="inputMedName col-auto" class="col-lg-3 col-form-label " for="mdaRegisNo1">1. MDA Device Registration No. <span style="color:red;">*</span></label>
<div class="col-6 col-lg-6">
<select name="mdaRegisNo" class="form-control " id = "mdaRegisNo1" select data-size="5" data-live-search="true">
<option > Select MDA Registration Number</option>
#foreach($devices as $key=>$device)
<option value="{{$key}}">{{$device->device_reg_no}}</option>
#endforeach
</select>
</div>
<input type='button' value='Seleted option' id='but_read'>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label ">2. Affected Device Name <span style="color:red;">*</span></label>
<div class="col-9 col-lg-9">
<input name="devName" type="text" class="form-control" >
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label ">3. Device intended use <span style="color:red;">*</span></label>
<div class="col-9 col-lg-9">
<input name="devUse" type="text" class="form-control" >
</div>
</div>
<div class="form-group row">
<label class="col-lg-3 col-form-label ">4. Class of Device<span style="color:red;">*</span></label>
<div class="col-9 col-lg-9">
<input name="devClass" type="text" class="form-control" >
</div>
</div>
RecallControlle.php
public function create()
{
$recall = Recall::latest()->first();
$ref_recall = 'MDA/Recall/P'.$this->getRefSuffix($recall);
//$devices = DB::table('devices');
$devices = Device::get();
$post = Device::query();
$device = DB::table('devices')->select('device_reg_no')->distinct()->get()->pluck('device_reg_no')->sort();
//dd($devices);
//return json_encode($devices);
return view('recall.create',['devices'=>$devices])->with([
'ref_recall' => $ref_recall,
'ref_mpr' => ''
]);
}
You have to use js to request data when your dropdown been selected.
Follow this doc to request data: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
pass your selected value to your api
get result from api
append value to input

including the appended variable to the data with other variable in ajax

Hello and good day everyone, I am having a problem in ajax. I have a variable named fd that contains object. But i cant find a way to put it together with other variable in "data:". I just want to pass the data of fd and also the other variables from other inputs of my form. Thank you very much.
$('#register_btn').click(function(e) {
var fd = new FormData();
var files = $('#image')[0].files[0];
fd.append('image',files);
var val1 = $('#email').val();
var val2 = $('#firstname').val();
var val3 = $('#middlename').val();
var val4 = $('#lastname').val();
var val5 = $('#emp_status').val();
var val6 = $('input[name=date_hired]').val();
var val7 = $('#account_type').val();
var val8 = $('#notes').val();
var val9 = $('#position').val();
var val10 = $('#cp_number').val();
var val11 = $('#tel_number').val();
var val12 = $('#address').val();
$.ajax({
type: 'POST',
url: 'process/add_employee_process.php',
contentType: false,
cache: false,
processData:false,
data: {email: val1, firstname: val2, middlename: val3, lastname: val4, emp_status: val5, date_hired: val6, account_type: val7, notes: val8, position: val9, cp_number: val10, tel_number: val11, address: val12,fd},
success:function(html) {
if(html=="Failed"){
$("#gifcheckmark").attr('src','../campfire.gif');
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#notif_message").text("Failed");
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
}
else{
$("#notif_message").text("Success");
$("#gifcheckmark").css('display','inline');
$("#gifcheckmark").css('width','inline');
$("#register_btn").css('display','none');
$("#decline_btn").css('display','none');
setInterval(successGif, 1600);
$('#qr').load('../phpqrcode/index.php');
$('#qr').show();
}
}
});
});
This is the form
<form role="form" style="width: 100%;">
<div class="box-body">
<div class="box-header with-border col-xs-12">
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group col-md-3">
<label for="">Email </label>
<input type="email" id="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group col-md-3">
<label for="">Firstname </label>
<input type="text" id="firstname" class="form-control" id="" placeholder="Firstname">
</div>
<div class="form-group col-md-3">
<label for="">Middlename </label>
<input type="text" id="middlename" class="form-control" id="" placeholder="Middlename">
</div>
<div class="form-group col-md-3">
<label for="">Lastname </label>
<input type="text" id="lastname" class="form-control" id="" placeholder="Lastname">
</div>
<div class="form-group col-md-3">
<label for="">Employee Status </label>
<input type="text" id="emp_status" class="form-control" id="" placeholder="Employee Status">
</div>
<div class="form-group col-md-3">
<label for="">Date Hired </label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" name="date_hired" class="form-control pull-right" id="datepicker">
</div>
</div>
<div class="form-group col-md-3">
<label for="">Account Type </label>
<input type="text" id="account_type" class="form-control" id="" placeholder="Account Type">
</div>
<div class="form-group col-md-3">
<label for="">Notes </label>
<input type="text" id="notes" class="form-control" id="" placeholder="Notes">
</div>
<div class="form-group col-md-3">
<label for="">Positions </label>
<input type="text" id="position" class="form-control" id="" placeholder="Positions">
</div>
<div class="form-group col-md-3">
<label for="">Cellphone Number </label>
<input type="text" id="cp_number" class="form-control" id="" placeholder="Cellphone Number">
</div>
<div class="form-group col-md-3">
<label for="">Telephone Number </label>
<input type="text" id="tel_number" class="form-control" id="" placeholder="Telephone Number">
</div>
<div class="form-group col-md-3">
<label for="">Address </label>
<input type="text" id="address" class="form-control" id="" placeholder="Address">
</div>
<div class="form-group col-xs-12">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" id="image" name="image">
</div>
</div>
<!-- /.box-body -->
<div class="col-xs-2">
<center><button type="button" id="confirm_btn" class="btn btn-primary" data-toggle="modal" data-target="#modal-default">
Submit
</button></center>
</div>
</form>
This is the add_employee_process.php
$db = mysqli_connect('localhost', 'root','','cjwebsolutions');
$image = $_FILES['image']['name'];
$target = "image/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
$emp_id = make_emp_id($_POST['date_hired']);
$_POST['emp_id'] = $emp_id;
// Required field names
$required_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
$data_insert_fields = array('email','firstname','middlename','lastname', 'emp_status', 'date_hired','account_type','notes','position','cp_number','tel_number','address','emp_id');
if (check_empty_fields($required_fields)) {
echo "Failed";
}
else
{
data_insert($data_insert_fields,"cj_accounts");
}

I have an issue when update a form in Spring boot

I want to update a form in spring boot - all input fields are successfully populated from the retrieved data but when I press 'submit' for update the system gives this error message.
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 07 09:41:44 IST 2017
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "updateApplication"
My DAO code:
public interface SLSNotificationRepository extends CrudRepository<SLSNotification, Integer> {
#Override
SLSNotification save(SLSNotification slsNotification);
#Override
SLSNotification findOne(Integer integer);
#Override
long count();
#Override
void delete(Integer integer);
#Override
void delete(SLSNotification slsNotification);
#Override
void delete(Iterable<? extends SLSNotification> iterable);
#Override
List<SLSNotification> findAll();
#Query("select a from SLSNotification a where a.slsiUnit in :unitList")
List<SLSNotification> getApplicationsByUnit(#Param("unitList")List <String> unitList);
#Query("select a from SLSNotification a where a.userId = :userId")
List<SLSNotification> getApplicationsByUserId(#Param("userId")String userId);
#Query("select a from SLSNotification a where a.slsNo = :slsNo")
SLSNotification getApplicationBySLSNumber(#Param("slsNo") String slsNo);
#Query("select a from SLSNotification a where a.importerVAT = :importerVAT group by slsNo")
List<SLSNotification> getproductByUserId(#Param("importerVAT")String importerVAT);
}
My service:
public boolean update(SLSNotification slsNotification) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
My controller is
#RequestMapping(path = "/updateApplication", method = RequestMethod.POST)
public String updateApplication(#ModelAttribute("applicationForm") #Valid SLSNotification slsNotification,
BindingResult result,
HttpSession session) {
slsiLogger.info("Request received to register new product. [{}]", slsNotification);
if (result.hasErrors()) {
slsiLogger.error("Rejecting the request due to binding errors, [{}]", result.getFieldErrors());
return "redirect:/applicationManage?";
}
if (applicationServices.update(slsNotification)) {
slsiLogger.info("Product registered successfully");
session.setAttribute(MESSAGE_KEY, "Product registered successfully");
} else {
session.setAttribute(MESSAGE_KEY, "Error occurred while registering the product");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
My JSP:
<form:form name="applicationForm" id="applicationForm" action="updateApplication" commandName="app" method="post">
<c:if test="${edit}">
<input type="hidden" id="snumber" name="snumber" value="${app.snumber}"/>
</c:if>
<div class="panel panel-default">
<div class="panel-body" >
<div class="row">
<label id="aaa" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name &
Address <div class="req" > *</div></label>
<label id="bbb" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name <div class="req" > *</div></label>
<div id="">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" value="" id="registered">Registered Manufacturer in SLSI</label>
</div>
<div id="regManu">
<select id="companies">
<c:forEach items="${manu}" var="com">
<option value="${com.manufacturerName}">${com.manufacturerName}</option>
</c:forEach>
</select>
</div>
<textarea name="manufacturer" class="form-control form-control-lg"
id="manufacturer"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="manufacture" name="manufacture" value="${app.manufacturer}"/>
<div class="help-block with-errors"></div>
</div>
<label for="exporterAddress" class="col-sm-2 col-form-label col-form-label-lg">Exporter Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="exporterAddress" class="form-control form-control-lg" id="exporterAddress"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="5" maxlength="254"></textarea><br/><br/>
<input type="hidden" id="exp" name="exp" value="${app.exporterAddress}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<br/> <label for="importerVAT" class="col-sm-2 col-form-label col-form-label-lg">Importer VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" type="text" name="importerVAT" id="importerVAT"
aria-describedby="importerVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.importerVAT}">
<div class="help-block with-errors"></div>
</div>
<label for="declarantVAT" class="col-sm-2 col-form-label col-form-label-lg">Declarant VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" name="declarantVAT" type="text" id="declarantVAT"
aria-describedby="declarantVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.declarantVAT}">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row" >
<label for="importerDetails" class="col-sm-2 col-form-label col-form-label-lg">Importer Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="importerDetails" class="form-control form-control-lg" id="importerDetails"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name and Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="imp" name="imp" value="${app.importerDetails}"/>
<div class="help-block with-errors"></div>
</div>
<label for="declarantDetails" class="col-sm-2 col-form-label col-form-label-lg">Declarant Name &
Address <div class="req"> *</div></label>
</div>
</div>
<div class="form-group row">
<label for="cusOffice" class="col-sm-2 col-form-label col-form-label-lg">CusDec No &
Date</label>
<div class="col-sm-2">
<input class="form-control" type="text" name="cusOffice " id="cusOffice " style="float:left;"
aria-describedby="importerVATHelp" placeholder=" Ex : KTIM1" value="${app.cusOffice}">
</div>
</div>
</div>
<div class="tabbable">
<br/>
<div class="row">
<div class="col-md-12">
<ul class="nav nav-pills">
<li class="active"><a href="#tab1" data-toggle="pill" style="text-decoration: none;">Product
Details</a></li>
<li>Consignment Details</li>
<li>Attachments</li>
</ul>
<br/>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="form-group row">
<label for="slsNo" class="col-sm-5 col-lg-2 col-xs-12 col-form-label col-form-label-lg">Relevant
SLS Standard No <div class="req"> *</div></label>
<div class="col-sm-3 col-sm-4">
<input class="form-control" type="text" id="slsNo" name="slsNo"
aria-describedby="slsNoHelp"
placeholder=" Enter SLS No here"
data-error="SLSI Standard No is required!" onkeyup="numbersOnly(this)" required value="${app.slsNo}">
<div class="help-block with-errors"></div>
</div>
<label for="slsiUnit" class="col-sm-1 col-form-label col-form-label-lg">
SLSI Unit <div class="req"> *</div></label>
<div class="col-sm-2">
<select class="form-control" id="slsiUnit" name="slsiUnit"
data-error="SLSI Unit is required!" required>
<option>UNIT1</option>
<option>UNIT2</option>
<option>UNIT3</option>
<option>UNIT4</option>
<option>UNIT5</option>
<option>UNIT6</option>
</select>
<input type="hidden" id="ut" name="ut" value="${app.slsiUnit}"/>
</div>
<label for="invoiceValue" class="col-sm-5 col-xs-6 col-md-5 col-lg-2 col-form-label col-form-label-lg">Invoice
Value (FOB) of the Product in US$ <div class="req"> *</div></label>
<div class="col-sm-6 col-md-3 col-lg-2 col-xs-6">
<div class="input-group">
<span class="input-group-addon">US$</span>
<input class="form-control" type="text" name="invoiceValue" id="invoiceValue"
aria-describedby="invoiceValueHelp"
placeholder="Value"
data-error="Invoice Value is required!" onkeyup="numbersOnly(this)" required value="${app.invoiceValue}"/>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group row">
<label for="invoiceValue" class="col-sm-4 col-xs-6 col-md-2 col-lg-2 ">Total
Quantity <div class="req"> *</div></label>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3">
<input class="form-control" type="text" name="totalQty" id="totalQty"
aria-describedby="totQtyHelp"
placeholder="Total Net Weight in Number"
data-error="Total Net Weight is required!" onkeyup="numbersOnly(this)" required value="${app.totalQty}">
</div>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3">
<select class="form-control" id="uom" name="uom" style="float:left;">
<option>KGM</option>
<option>UNITS</option>
<option>LITERS</option>
<option>CANS</option>
</select>
<input type="hidden" id="um" name="um" value="${app.uom}"/>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label for="shippingMarks" class="col-sm-12 col-form-label col-form-label-lg">Shipping
Marks & Container No/s </label>
<textarea name="marksNumber" class="form-control form-control-lg"
id="marksNumber" placeholder="If no of containers greater than 10 please attach the container numbers as an attachment"
data-error="Shipping marks are required!" maxlength="250" rows="5" ></textarea>
<input type="hidden" id="shims" name="shims" value="${app.marksNumber}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label for="productDesc" class="col-sm-12 col-form-label col-form-label-lg">Product
Description (Max 250 charactors) <div class="req"> *</div></label>
<textarea value="${app.productDesc}" name="productDesc" class="form-control form-control-lg"
id="productDesc"
placeholder="Enter Product Description with brand,model/Type,size/s, quantity, Pkg.Type etc. here"
data-error="Product Description is required!" maxlength="250" required rows="5" ></textarea>
<input type="hidden" id="product" name="product" value="${app.productDesc}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label for="purpose"
class="col-sm-12 col-form-label col-form-label-lg">Purpose <div class="req"> *</div></label>
<select class="form-control" id="purpose" name="purpose"
data-error="Purpose is required!" required>
<option>Commercial</option>
<option>Personal</option>
<option>Project</option>
<option>Charity</option>
<option>Further Processing</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="hsCode" class="col-sm-12 col-form-label col-form-label-lg">HS
Code <div class="req"> *</div></label>
<input class="form-control" type="text" id="hsCode" name="hsCode"
aria-describedby="hsCodHelp" placeholder=" Please enter HS Code here"
data-error="HS Code is required!" required value="${app.hsCode}">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label for="issuerQltyCert" class="col-sm-12 col-form-label col-form-label-lg">Issuer
of Product/Quality Certificate <div class="req"> *</div></label>
<input class="form-control" type="text" id="issuerQltyCert" name="issuerQltyCert"
aria-describedby="issuerCertHelp"
placeholder=" Enter the Organization Issued the Certificate"
data-error="Organization is required!" required maxlength="254" value="${app.issuerQltyCert}">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="certRefNo" class="col-sm-12 col-form-label col-form-label-lg">Product
Certificate Ref.No <div class="req"> *</div></label>
<input class="form-control" type="text" id="certRefNo" name="certRefNo"
aria-describedby="certRefNoHelp"
placeholder=" Please enter product certificate No."
data-error="Product certificate No is required!" required value="${app.certRefNo}" >
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="form-group row">
<label for="vessel" class="col-sm-3 col-md-2 col-xs-7 col-form-label col-form-label-lg">Vessel
Name <div class="req"> *</div></label>
<div class="col-md-2">
<input class="form-control" type="text" name="vessel" id="vessel"
aria-describedby="vesselHelp" placeholder=" Vessel Name"
data-error="Vessel Name & Date is required!" required maxlength="254" value="${app.vessel}" >
</div>
<label for="blNo" class="col-sm-5 col-md-2 col-xs-6 col-lg-2 col-form-label col-form-label-lg">Bill Of Lading
No <div class="req"> *</div></label>
<label for="blNo" class="col-sm-12 col-md-2 col-xs-12 col-form-label col-form-label-lg">Date of B/L <div class="req"> *</div></label>
<div class="col-sm-1">
<input type="text" class="datep" format="YYYY-MM-dd" style="float:left;"
readonly='true' name="blDate" id="blDate">
</div>
</div>
<input class="form-control" type="text" name="loadingPort" id="loadingPort"
aria-describedby="loadPortHelp"
placeholder=" Please enter Port of Loading here"
data-error="Port of Loading is required!" required value="${app.loadingPort}">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" id="submit" class="btn btn-success pull-right">SAVE CHANGES</button>
</div>
</div>
</form:form>
How do I get the form update to work?

form_is.valid is false(django)

I have the below code which is inheriting from models for modelform, but failing to pass the condition for valid.
Model.py
class contact(models.Model):
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
email = models.EmailField()
phone = models.IntegerField()
message = models.CharField(max_length=100)
def __str__(self):
return self.fname
urls.py
urlpatterns = [
url(r'^$', 'asp.views.index', name='root'),
url(r'^contact/', 'asp.views.contact', name='contact'),
url(r'^new$', 'asp.views.new_user', name='new'),
url(r'^admin/', include(admin.site.urls)),
]
where asp is my application
def contact(request):
return render(request, "contact.html", {})
def new_user(request):
print( '$' * 100)
if request.method == 'POST':
form = contactform(request.POST or None)
print( '*' * 10)
if form.is_valid():
print( '!' * 10)
else:
form = contactform()
return render(request, "index.html", {'form':form})
For which $,* was printing, but not passing the condition for valid.
forms.py
class contactform(forms.ModelForm):
class Meta:
model = contact
exclude = ()
Below is my html page
<form class="form-horizontal" action="/new" method="post">{% csrf_token %}
{{ form }}
<fieldset>
<legend class="text-center header">Contact us</legend>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="fname" name="name" type="text" placeholder="First Name" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="lname" name="name" type="text" placeholder="Last Name" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="email" name="email" type="text" placeholder="Email Address" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<input id="phone" name="phone" type="text" placeholder="Phone" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<textarea class="form-control" id="message" name="message" placeholder="Enter your massage for us here. We will get back to you within 2 business days." rows="7"></textarea>
</div>
</div>
</fieldset>
</form>
Thanks in advance.

Resources