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})
Related
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)
}
})
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)
I want to display the content of an announcement inside a modal when a user clicked on the announcement list.
This will be the trigger for the modal in my announcement_list.html:
<form name="form" action="#" id="form_have_product_{{y.id}}" method="POST">
{% csrf_token %}
View
</form>
This is my function in my views.py:
def get_announcement(request, pk):
announcement = Announcement.objects.filter(announcement_id=pk)
context = {
'title': announcement.title,
'about': announcement.about,
'author': announcement.author,
'post_date': announcement.post_date
}
return render(request, 'announcement-details-modal.html', context)
For the urls.py:
urlpatterns = [path('announcement/<int:pk>/', get_announcement, name='announcement-detail'),]
And this is the function for when the user clicks on the announcement list:
$(".view-announcement").on("click", function() {
var target_url = $(this).attr("data-url");
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$.ajax({
url: target_url,
headers:{
"X-CSRFToken": csrftoken
},
success: function(data) {
$("#modal").modal("toggle");
$("#modal-content").html(data);
}
});
});
Currently this code returns the server responded with a status of 500 (Internal Server Error)
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");
}
});
});``
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 %}