getting empty dictionary on POST ajax - django

I am trying to delete some elements in database when user clicks on delete icon but as i am sending id through POST request , i am getting empty dictionary ,
{% for skills in seeker_skills %}
<div class="col-md-4">
<button class="btn btn-info mx-2">{{skills.skill_name}}<span class="badge badge-dark ">{{skills.skill_level}}</span></button><span><i class="fas fa-trash-alt delete_skill" data-attr={{skills.id}} style="cursor: pointer;"></i></span>
</div>
{% endfor %}
updated snippet , i am calling it on click
Ajax code
let delete_class_list = $('.delete_skill')
delete_class_list.click(function(e){
let value = this.getAttribute("data-attr")
let contain_icon = this
let contain_label = contain_icon.parentElement.previousSibling
console.log(contain_label)
$.ajax({
url:'/delete_skill/',
method : 'POST',
data: {
skill_id:value
},
dataType: "json",
contentType: "application/json",
success :function(data){
console.log(data)
contain_label.remove()
contain_icon.remove()
}
,
error:function(e){
console.log(e)
}
})
})
My view
#csrf_exempt
def delete_skill(request):
if request.method == 'POST':
data = {}
print('method is post')
job_id = request.POST.get('skill_id')
print(job_id)
try:
Job_Skillset.objects.get(id=job_id).delete()
data['status'] = 'deleted'
except ObjectDoesNotExist:
data['status'] = 'nodata'
return JsonResponse(data,safe=False)

You're setting your content type to application/json which is incorrect, remove it.
$.ajax({
url:'/delete_skill/',
method : 'POST',
data: {
skill_id:value
},
dataType: "json",
success :function(data){
console.log(data)
contain_label.remove()
contain_icon.remove()
}
,
error:function(e){
console.log(e)
}
})

Related

submitting django crispy form with file field and some other text fields using fetch and then

I am trying to submit my crispy form using fetch and then methods to django backend. All my fields are submitting to the server. but files are shown as empty fields in the server.
below, is my front end from
{{ photo.media }}
<form action="" method="post" class="form my-4 px-2" enctype="multipart/form-data" id="photo_form"
onsubmit="">
{% csrf_token %}
{{photo|crispy}}
<input type="submit" value="Add" class="btn btn-primary btn-lg">
</form>
Here is the ajax request I made
<script>
const photoForm = document.querySelector('#photo_form');
console.log(photoForm.values);
photoForm.addEventListener('submit', (event) => {
event.preventDefault();
const photoFormData = new FormData(photoForm);
photoFormData.forEach((value, key) => {
console.log(key + ': ' + value);
});
fetch("{% url 'add_photo' %}", {
method: 'POST',
body: photoFormData,
contentType: false,
processData: false,
})
.then((response) => response.json())
.then((data) => {
console.log(data);
if (data.result == 'success') {
$('.modal-body').html('Form submission was successful!');
$('#modal-dialog').modal('show');
photoForm.reset();
} else {
$('.modal-body').html('There was an error with the form submission.');
$('#modal-dialog').modal('show');
}
});
});
</script>
Below, is the model I Made
class Photos(models.Model):
photo_title = models.CharField(max_length=50, blank=False)
photo_description = models.CharField(max_length=50, blank=False)
photo_date = models.DateField(blank=False)
photo_location = models.CharField(max_length=50, blank=False)
photo_file = models.ImageField(upload_to='photos', blank=False)
def __str__(self):
return self.photo_title
Below, is the view function
""" ajax add photo event to home wall """
def add_photo(request):
if request.method == 'POST':
response_data = {}
photoForm = UploadPhotosForm(request.POST)
print(photoForm.is_valid())
print(photoForm.errors)
if photoForm.is_valid():
photoForm.save()
response_data['result'] = 'success'
print(response_data)
return HttpResponse(
JsonResponse(response_data),
)
else:
response_data['result'] = 'error'
print(photoForm.errors)
return HttpResponse(
JsonResponse(response_data),
)
While I tried to figure out the problem, I got these outputs
from client side
csrfmiddlewaretoken: xDJ7qlvfOgaPta6VXkIH03QlT1AybEQ46xcC2ri09MO4F7DbBPGbeNehMrJa3Rjy
(index):141 photo_title: sadfsf
(index):141 photo_description: sfsfse
(index):141 photo_date: 2022-12-22
(index):141 photo_location: adsafd
(index):141 photo_file: [object File]
(index):144
POST http://127.0.0.1:8000/manager/add/photo/ 500 (Internal Server Error)
(anonymous) # (index):144
VM750:1
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Promise.then (async)
(anonymous) # (index):149
from server side
False
<ul class="errorlist"><li>photo_file<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
<ul class="errorlist"><li>photo_file<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
[21/Dec/2022 15:09:10] "POST /manager/add/photo/ HTTP/1.1" 200 19
can someone help me out to figure out the problem?
In your post method, change to:
photoForm = UploadPhotosForm(request.POST,request.FILES)

search data using ajax and django and redirect to related pages

I am building a website and I want to implement searching. I want the user to enter some text and want to show suggestions using ajax. when the user click on specific product or category I want to redirect the user to related page. Here is what I have done so far:
$(function () {
$("#search").autocomplete({
source: "{% url 'ajax-search' %}",
select: function (event, ui) { //item selected
AutoCompleteSelectHandler(event, ui)
},
minLength: 5,
});
});
<div class="search">
<label for="search"></label>
<input type="text" oninput="" style="height: 36px" class="searchTerm" placeholder="What are you looking for?" name="searchtext" id="search">
<button type="submit" class="searchButton">
<i class="fa fa-search"></i>
</button>
</div>
path('ajax/search', views.autocompleteModel, name='ajax-search'),
def autocompleteModel(request):
if request.is_ajax():
q = request.GET.get('term', '')
lookups = Q(name__icontains=q) | Q(category__name__icontains=q)
products = Product.objects.filter(lookups).distinct()
results = []
for product in products:
place_json = {}
place_json = product.name
product_url = 'prodcuts/product/' + str(product.id)
results.append(place_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
In your javascript section you have to do something like this:
$(function () {
$("#search").autocomplete({
source: "{% url 'ajax-search' %}",
select: function (event, ui) {
window.location.href = ui.item.value;
},
minLength: 5,
});
});
And Python code part should look like this:
results = []
for product in products:
item = dict(
label = product.name,
value = '/products/product/' + str(product.id)
)
results.append(item)
data = json.dumps(results)

set the value of the input field in the action of the form in django

I have created the modelforms with the name field and i want the retrieve the name entered in the input field to be as a url in the django
forms.py
class githubform(ModelForm):
class Meta:
model = github
fields=['name']
model.py
class github(models.Model):
name = models.CharField(max_length=200)
views.py
def github(request):
gform = githubform(request.POST or None)
if gform.is_valid():
gform.save()
return render(request,'formsapp/github.html',{'gform':gform})
github.html
<form method="post" action="https://api.github.com/users/{{ gform.data.name }}">
{% csrf_token %}
{{ gform.as_p }}
<button type="submit">signup</button>
</form>
ccccc
now i want the value of the input field entered by the user in place of gform.data.name and i am stuck in getting the value entered by the user into action url.
can anyone help me to sort it out
delete method and action on form
<form id="form">
then submit with jquery
$(document).on('submit', '#form', function() {
const value = $(input[name='name']).val()
$.ajax({
type: 'POST',
url: `https://api.github.com/users/${value}`,
data: {
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success:function() {
console.log("success");
},
error: function(data) {
console.log("error");
}
});
});``

Ajax goes to url instead of changing data Django

I'm using ajax in Django to activate add to favorites button, here are my files
urls
path('<int:pk>/favorite_item/', views.favorite_item, name='favorite_item'),
views.py
#login_required
def favorite_item (request, pk):
favitem = get_object_or_404(Item, pk=pk)
data = {
'is_fav': Favorite.objects.filter(user=request.user, item=favitem).exists(),
}
if data ['is_fav']:
Favorite.objects.get(user=request.user, item=favitem).delete()
else:
new_entry = Favorite.objects.create(item=favitem, user=request.user)
return JsonResponse(data)
finally HTML
only the part of the script
{% block javascript %}
<script>
$("#add_to_fav").click(function () {
console.log( $(this).val() );
});
$.ajax({
url: form.attr("data-favorite_item-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
$('.results').html(data);
},
});
</script>
{% endblock %}
Now when I click the element that should trigger the whole action, the function is already working and the item is removed or added to db, but it takes me to another page which only has 1 sentence ({"is_fav": true}) or ({"is_fav": false})
You need to use preventDefault to stop your browser from actually going to the linked page when the link is clicked. You need to change lines 3 and 4 of the code you included like this:
{% block javascript %}
<script>
$("#add_to_fav").click(function (event) {
event.preventDefault();
console.log( $(this).val() );
});
$.ajax({
url: form.attr("data-favorite_item-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
$('.results').html(data);
},
});
</script>
{% endblock %}

Render template with context after creating objects

Consider a textarea input to enter emails.
The view has a forloop: for each email the view tries to create a user. Then, if the user is created, I append it to my array "newUers", if the user already exists, I append it to the "alreadyUsers" array.
When the loop ends, I want to render a view with these arrays. But it does not work...
The users are correctly created but the view does not render the template.
Any idea?
invitations.html: a textarea with an an ajax call on submit
<div id="invitations">
<label>Enter your clients email</label>
<textarea v-model="invitations" class="textarea" id="invitations" name="invitations"></textarea>
</div>
<div>
<input id="send" type="submit" value="Save" #click="submit()">
</div>
user_invitation.js: the ajax call (based on Vue)
var vue = new Vue({
el: '#invitations',
data: {
invitations: '',
},
methods: {
submit: function () {
var self = this;
$.ajax({
type: 'POST',
url: '/accounts/invitations/create/',
data: {
invitations: this.invitations,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
context: this,
success: function () {
console.log("ajax success");
},
error: function () {
console.log("ajax error");
}
})
}
}
});
views.py
def InvitationCreateView(request):
newUsers = []
alreadyUsers = []
for client in request.POST['invitations'].split('\n'):
try:
# Get informations for creating the User
user = User.objects.create(
username=client,
email=client,
)
user.groups.add(Group.objects.get(name='Clients'))
user.save()
newUsers.append(client)
# Check if user already exists
except IntegrityError:
alreadyUsers.append(client)
return render(request, 'accounts/agent_invitations_confirmation.html',
{"newUsers": newUsers, "alreadyUsers": alreadyUsers})