I'm trying to validate a field while typing based on another question (How to validate django form field while it is typing?).
The js doesn't cal validation view
form
{{ form.num }}
<p id="validate_number" class="help is-danger is-hidden ">nome já utilizado</p>
js
<script>
$('#id_num').on('input', function () {
var id_number = $(this).val();
$.ajax({
url: '{% url 'validate-num' %}',
data: {
'num': id_number
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
$("#validate_number").show();
document.getElementById('id_num').style.borderColor = "red";
document.getElementById("submit_change").disabled = true;
}
else {
$("#validate_number").hide();
document.getElementById('id_num').style.borderColor = "#e7e7e7";
document.getElementById("submit_change").disabled = false;
}
}
});
});
</script>
url.py
urlpatterns = [
# ...
path('validatenum/', validate_inventory_number, name='validate-num'),
# ...
]
view
def validate_inventory_number(request):
number = request.GET.get('num', None)
data = {
'is_taken': InventoryNumber.objects.filter(num=number).exists()
}
return JsonResponse(data)
Related
When i send data from ajax to view in Django I am getting none in data. What seems to be the problem. Here is mycode. Where as if i remove processData: false, contentType: false, then data is printed successfully but on file it gives error.
Ajax code
<script>
function submit_data()
{
var type = $('#type').val();
var subtype = $('#subtype').val();
var name = $('#name').val();
var price = $('#price').val();
var weight = $('#weight').val();
var details = $('#details').val();
var picture1 = $('#image1')[0].files[0];
var picture2 = $('#image2')[0].files[0];
var picture3 = $('#image3')[0].files[0];
var vedio_url = $('#vedio_link').val();
alert(picture1)
$.ajax({
url: '/add_record/',
type: 'POST',
headers: { "X-CSRFToken": '{{csrf_token}}' },
processData: false,
contentType: false,
data: {
type,
subtype,
name,
price,
weight,
details,
picture1,
picture2,
picture3,
vedio_url,
},
success: function (response) {
alert("datauploaded successfully!")
},
error: function(){
alert('error')
}
});
}
</script>
View code
def add_record(request):
print("Yes i am here")
type = request.POST.get('type')
subtype = request.POST.get('subtype')
name = request.POST.get('name')
price = request.POST.get('price')
weight = request.POST.get('weight')
details = request.POST.get('details')
picture1 = request.FILES.get('picture1')
picture2 = request.FILES.get('picture2')
picture3 = request.FILES.get('picture3')
vedi_url = request.POST.get('vedio_url')
print (picture1)
print(type)
print(request.POST)
return JsonResponse({'message':'success'},status=200)
Error:
Yes i am here
None
None
<QueryDict: {}>
its returning none, Why is that?
Ajax without files:
Your JS data element should be a dictionary, also remove processData and contentType parameters.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<input type="text" id="name"/>
<button type="button" id="send" onclick="submit_data()">Send<button/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function submit_data()
{
var name = $('#name').val();
$.ajax({
url: '/add_record/',
type: 'POST',
headers: { "X-CSRFToken": '{{csrf_token}}' },
data: {
'name': name,
},
success: function (response) {
alert(response.data)
},
error: function(){
alert('error')
}
});
}
</script>
</body>
</html>
views:
from django.shortcuts import render
from django.http import JsonResponse
def form_record(request):
return render(request, "mytemplate.html", {})
def add_record(request):
print("Yes i am here")
name = request.POST.get('name')
print(f"Post: {request.POST}")
return JsonResponse({'data': name},status=200)
Ajax with files:
Because you are sending binary data you should to use FormData:
function submit_data()
{
var name = $('#name').val();
var formData = new FormData() // changes here
formData.append('name', name) // and here
$.ajax({
url: '/add_record/',
type: 'POST',
headers: { "X-CSRFToken": '{{csrf_token}}' },
contentType: false, // and here
enctype: 'multipart/form-data', // and here
processData: false, // and here
cache: false,
data: formData, // <-- carefully here
success: function (response) {
alert(response.data)
},
error: function(){
alert('error')
}
});
}
Result:
you can do with a lot of entries please because I have a more complex problem.
in my case I have 6 entries when I enter an entry I have an output in the form of a table and at the end I have to make a final request which will take into account the rows that I have selected.
Excuse my English.
my js :
function submit_data(){
list_fournisseurs = selectcheck();
list_entrepot = selectcheck1();
var numdoc = $('#numdoc').val();
var reference = $('#reference').val();
var reference_doc = $('#reference_doc').val();
var date_debut = $('#date_debut').val();
var date_fin = $('#date_fin').val();
var format_fournisseur = new FormData();
var format_entrepot = new FormData();
var format_numdoc = new FormData();
var format_reference = new FormData();
var format_reference_doc = new FormData();
var format_date_debut = new FormData();
var format_date_fin = new FormData();
const format = [
format_fournisseur.append('list_fournisseurs', list_fournisseurs),
format_entrepot.append('list_entrepot', list_entrepot),
format_numdoc .append('numdoc', numdoc),
format_reference.append('reference', reference),
format_reference_doc.append('reference_doc', reference_doc),
format_date_debut.append('date_debut', date_debut),
format_date_fin.append('date_fin', date_fin),
]
$.ajax({
type : 'POST',
url : 'fournisseur_ajax',
data : {
'csrfmiddlewaretoken': csrf,
'format' : format,
},
//processData: false,
success : (res) =>{
console.log('res.data',res.data)
},
error : (err) =>{
console.log(err)
},
})
}
my view
if request.method == "POST" :
check_list_fournisseurs = request.POST.getlist("format_fournisseur[]")
print("########## voici la liste ###########",check_list_fournisseurs)
check_list_entrepot = request.POST.getlist("format_entrepot[]")
print("########## voici la liste ###########",check_list_entrepot)
print("numdoc ",num_doc)
print("item_ref",item_ref)
print("item_doc",item_doc)
print("date_depart", date_debut)
print("date_fin",date_fin)
context ={'check_list_entrepot':check_list_entrepot,"check_list_fournisseurs":check_list_fournisseurs, 'num_doc':num_doc, 'item_ref':item_ref, 'item_doc':item_doc, 'date_debut':date_debut, 'date_fin':date_fin}
return render(request,"final.html",context)
I am trying to collect books in a shelf object. However when i try to add a book, the page does nothing and i get this error in my console "Uncaught (in promise) TypeError: Cannot read property 'push' of undefined". Need help with this.
main.js
function sendRequest(url,method,data) {
var r = axios({
method: method,
url: url,
data: data,
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
return r
}
var app = new Vue({
el : '#app',
data: {
book: '',
books: [
{title: 'one'},
{title: 'two'}
]
},
created(){
var vm = this;
var r = sendRequest('','get')
.then(function(response){
vm.books = response.data.books;
})
},
methods: {
createBook(){
var vm = this;
var formData = new FormData();
formData.append('title', this.book);
sendRequest('','post',formData)
.then(function (response) {
vm.books.push(response.data.book); //PROBLEM HERE
vm.book = '';
})
}
}
})
views.py
def add_book(request, shelf_id):
context = {}
if request.POST:
shelf = get_object_or_404(Shelf, pk=shelf_id)
book_form = BookCreation(request.POST)
temp = book_form.save(commit=False)
temp.shelf = shelf
temp.save()
if book_form.is_valid():
books = book_form.save()
return JsonResponse({'book': model_to_dict(books)},status=200)
return render(request, 'shelf/addBook.html')
url.py
path('<int:shelf_id>/create_book', add_book, name='addbook'),
Apparently the issue was with me using if request.POST instead of request.method =='POST' in my backend.
def add_book(request, shelf_id):
context = {}
if request.method == 'POST': //THIS IS WORKING CODE
shelf = get_object_or_404(Shelf, pk=shelf_id)
book_form = BookCreation(request.POST)
temp = book_form.save(commit=False)
temp.shelf = shelf
temp.save()
if book_form.is_valid():
books = book_form.save()
return JsonResponse({'book': model_to_dict(books)},status=200)
return render(request, 'shelf/addBook.html')
Each form's input is associated with a unique data-comment-pk. I'm trying to access the value of data-comment-pk of the input which is submitted. Currently, the AJAX success function's alert(comment_pk) is only fetching me the comment_pk of the first form. How can I access the comment_pk of the form which is submitted instead of getting the comment_pk of the first form?
html template
{% for comment in object_list %}
<h3>{{comment.comment}} by {{comment.username}}</h3>
<form class="score-form">
<input type="submit" value="Up" name="up" class="Up" data-comment-pk="{{comment.pk}}" />
<input type="submit" value="Down" name="down" />
</form>
{% endfor %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script>
$(".score-form").submit(function (e) {
e.preventDefault();
var comment_pk = $(".Up").attr("data-comment-pk");
var url = comment_pk + "/vote";
console.log(url)
$.ajax({
type: 'GET',
url: url,
data: { "up": 'UP' },
success: function (response) {
if (response["valid"]) {
alert(comment_pk);
}
},
error: function (response) {
console.log(response)
}
})
})
</script>
models.py
class CommentModel(VoteModel, models.Model):
comment = models.TextField()
username = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
class CommentView(ListView):
model = CommentModel
def comment_vote(request, comment_id):
if request.is_ajax and request.method == "GET":
# do some stuff
return JsonResponse({"valid": True}, status=200)
Here is the solution to this problem :
var comment_pk = $(".Up", this ).attr("data-comment-pk");
Using this will return the current HTML element.
try: add "this" to before .Up in the comment_pk.
let me know if it works.
this- will get the currect form that have been submit and get the .Up Class
<script>
$(".score-form").submit(function (e) {
e.preventDefault();
var comment_pk = $("this .Up").attr("data-comment-pk");
var url = comment_pk + "/vote";
console.log(url)
$.ajax({
type: 'GET',
url: url,
data: { "up": 'UP' },
success: function (response) {
if (response["valid"]) {
alert(comment_pk);
}
},
error: function (response) {
console.log(response)
}
})
})
</script>
JS
$(function(){
var count=1;
$("#btn").click(function(){
count++;
})
})
views.py
def setparam(request):
counts=range(1,count)
eg.
Like this I want use JS's count to view.py .How can I get it ,is it possible?
You need send this to server.
I guess you ajax for your example.
JS
function send_cont(cont) {
$.ajax({
url: '{% url "your_app.views.your_view" %}',
type: "GET",
data: {
cont: cont
},
success: function (json) {
//Something
},
error: function (json) {
//Something
}
});
}
View
def your_view(request):
cont = request.GET.get('cont'))
#More code
I use this light sortable plugin to sort my data by drag and drop
http://farhadi.ir/projects/html5sortable/
Now, how to update my sort order
$('.sortable').sortable().bind('sortupdate', function() {
//Triggered when the user stopped sorting and the DOM position has changed.
});
views.py
def filter_order(request):
if request.method == 'POST':
order = request.POST.getlist('filter[]')
count = 0
for id in order:
count += 1
filter = FilterModel().objects.get(pk=id)
filter.sort_order = count
filter.save()
return HttpResponse('Successfully updating rules order.')
else:
return HttpResponse("Error updating rules order.")
urls.py
urlpatterns = patterns('transactions.views',
............
url(r'^filter-order/$', 'filter_order',
name='filter_order'),
)
rules.html
<ul class="sortable" id="filter-items">
{% for filter in filters %}
<li id="{{ filter.id }}">{{filter.rules}}</li>
{% endfor %}
</ul>
<script>
$('.sortable').sortable().bind('sortupdate', function() {
datas = new Array();
var i = 0;
$('#filter-items li').each(function() {
datas[i] = $(this).attr('id');
i++;
});
$.ajax({
type: "POST",
data: {
'filter[]': datas,
'csrfmiddlewaretoken': '{{csrf_token}}'
},
url:"/transactions/filter-order/",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data) {
notify('', 'Successfully updating rules order.', { autoClose: true, delay: 1000 });
},
error: function(ts) {
notify('', ts.responseText, { autoClose: true, delay: 1000 });
}
});
});
</script>