Обновление данных с помощью Django и AJAX
У меня проблема с созданием поля выбора в поле ввода из данных Django. models.py выглядит следующим образом:
class Manifold_monitoring(models.Model):
MFD_type = models.ForeignKey(Manifo_types , on_delete=models.CASCADE)
DATE_TEST = models.DateField()
Pressure_MFD = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True)
Pressure_SP = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True)
.....
def __str__(self):
return str(self.MFD_type.MFDsID.MFDsID +' '+ self.MFD_type.Type +' '+ self.MFD_type.Fluid_N)
class Meta:
ordering = ('-post_date',)
unique_together=[['MFD_type','DATE_TEST']]
и обновление views.py:
class UpdManifold_Monto(View):
form_class = Manifold_monitoring_F
def get(self,request, pk, *args, **kwargs):
if request.is_ajax():
task = Manifold_monitoring.objects.get(pk=pk)
task.delete()
return JsonResponse({"message":"success"})
return JsonResponse({"message": "Wrong request to delete"})
def post(self,request, pk, *args, **kwargs):
if request.is_ajax():
task = Manifold_monitoring.objects.get(pk=pk)
print('request.is_ajax()1', task.MFD_type_id)
data = {
"MFD_type_id": task.MFD_type_id,
"DATE_TEST" :task.DATE_TEST,
"Pressure_MFD":task.Pressure_MFD,
"Pressure_SP":task.Pressure_SP
}
print('request.is_ajax()2', task.MFD_type ,data )
form = self.form_class(request.POST, initial=data)
if form.is_valid():
MFD_type = form.cleaned_data['MFD_type']
DATE_TEST = form.cleaned_data['DATE_TEST']
Pressure_MFD = form.cleaned_data['Pressure_MFD']
Pressure_SP = form.cleaned_data['Pressure_SP']
print('request.is_ajax()3', MFD_type)
if form.has_changed():
task.MFD_type_id = MFD_type
task.DATE_TEST = DATE_TEST
task.Pressure_MFD = Pressure_MFD
task.Pressure_SP = Pressure_SP
task.save()
return JsonResponse({"message": "success"})
return JsonResponse({"message":"No change"})
return JsonResponse({"message":"Failed"})
return JsonResponse({"message": "Wrong request"})
HTML-код формы редактирования:
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLable" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="formEdit" action="">
{% csrf_token %}
<div class="modal-body">
<div class="form-group validate">
<input type="text" name="MFD_type" class="form-control" placeholder="Manifold">
<small class="text-red text-muted mySpan"></small>
</div>
<div class="form-group validate">
<input type="date" name="DATE_TEST" class="form-control" placeholder="Control Date">
<small class="text-red text-muted mySpan"></small>
</div>
<div class="form-group validate">
<input type="text" name="Pressure_MFD" class="form-control" placeholder="Pressure (bar)">
<small class="text-red text-muted mySpan"></small>
</div>
<div class="form-group validate">
<input type="text" name="Pressure_SP" class="form-control" placeholder="SP Pressure (bar)">
<small class="text-red text-muted mySpan"></small>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary btnUpdate">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
так как добавление и удаление изображений работает нормально. Итак, у меня есть этот список из базы данных в виде выпадающего списка (выбор).
последний скрипт AJAX и Jquery:
<script>
//Edit Function
$("#table_id tbody").on("click", ".link-edit", function(e){
e.preventDefault();
var $this = $(this);
let MFD_type = $this.parents(".record").find('td').eq(0).text();
let DATE_TEST= $this.data('start');
let Pressure_MFD = $this.parents(".record").find('td').eq(2).text();
let Pressure_SP= $this.parents(".record").find('td').eq(3).text();
$("#formEdit input[name='MFD_type']").val(MFD_type);
$("#formEdit input[name='DATE_TEST']").val(DATE_TEST);
$("#formEdit input[name='Pressure_MFD']").val(Pressure_MFD);
$("#formEdit input[name='Pressure_SP']").val(Pressure_SP);
$("#formEdit").attr("action", $this.attr('href'));
$("#editModal").modal("show");
return false;
});
$("#formEdit").on("submit", function(e){
e.preventDefault();
e.stopPropagation();
var $this = $(this);
var valid = true;
$('#formEdit input').each(function() {
let $this = $(this);
if(!$this.val()) {
valid = false;
$this.parents('.validate').find('.mySpan').text('The '+$this.attr('name').replace(/[\_]+/g, ' ')+' field is required');
}
});
if(valid){
let data = $this.serialize();
$.ajax({
url: $this.attr("action"),
type: "POST",
data: data,
dataType: "json",
success: function(resp){
if(resp.message === "success"){
alert("Updated successful");
$('#editModal .close').click();
}
else{
alert(resp.message);
}
},
error: function(resp){
console.log("Something went wrong");
}
});
}
return false;
});
</script>
Я хочу сделать ввод первого поля в виде выбора MFD_type
?
как мне это сделать? и правильна ли моя функция ANAX и UpdManifold_Monto?
Я подготовил список Dynamic Dependent Dropdown List. поэтому мои представления будут
def AddManifold_Monto(request):
form = Manifold_monitoring_F()
DrobdownMFD_type = Manifo_types.objects.exclude(Fluid_N = 'Stock')
model = Manifold_monitoring.objects.filter( DATE_TEST__exact= datetime.date.today())
context={
'title':'Manifold Monitoring',
'model':model,
'form': form,
'DrobdownMFD_type':DrobdownMFD_type
}
return render(request,'Home/Production_Ser/MFD_Monitor/ADDMFD_Monitor.html',context)
и в HTML форме я заменил ввод на следующее:
<select id="id_MFD_typeS" name="MFD_typeS" class="select-manifold form-control" required placeholder="Manifold">
<option value=""></option>
{% for brand in DrobdownMFD_type %}
<option id="{{ brand.id }}" value="{{ brand.id }}">
{{ brand.MFDsID }}
</option>
{% endfor %}</select>
<small class="text-red text-muted mySpan"></small>
Так что все работает, но когда я изменяю и обновляю значение, оно не сохраняется
из функции обновления представления я просто вывел значения формы
form = self.form_class(request.POST, initial=data)
print(form)
и это дает мне полный список?
> <tr><th><label for="id_MFD_type">Manifold:</label></th><td><ul
> class="errorlist"><li>This field is required.</li></ul><select
> name="MFD_type" required id="id_MFD_type"> <option value=""
> selected>---------</option>
>
> <option value="14">AMA CTR HP Prod</option>
>
> <option value="15">AMA CTR HP Selectif</option>
>
> <option value="16">AMA CTR BP Prod N1</option>
>
> <option value="17">AMA CTR BP Prod N2</option>
>
> <option value="18">AMA CTR BP Selct N1</option>
>
> <option value="19">AMA CTR BP Selct N2</option>
>
> <option value="20">AMA MFDS</option>
>
> <option value="21">AMA MFDS</option>
>
> </select></td></tr> <tr><th><label for="id_DATE_TEST">Control
> Date:</label></th><td><input type="date" name="DATE_TEST"
> value="2021-10-28" class="form-control" required id="id_DATE_TEST"
> /></td></tr> <tr><th><label for="id_Pressure_MFD">Pressure
> (bar):</label></th><td><input type="number" name="Pressure_MFD"
> value="33" step="any" id="id_Pressure_MFD" /></td></tr> <tr><th><label
> for="id_Pressure_SP">SP Pressure (bar):</label></th><td><input
> type="number" name="Pressure_SP" value="33" step="any"
> id="id_Pressure_SP" /></td></tr>