I need some help regarding button clicks and boolean value changes.
My model:
class Topic(models.Model):
subject = models.CharField(max_length=255)
category = models.CharField(max_length=255)
last_updated = models.DateTimeField(auto_now_add=True)
starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics')
slug = models.SlugField(unique=True)
isReported = models.BooleanField(default=False)
startPrice = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')])
I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button:
<button type="submit" class="btn btn-primary btn-block">Report</button>
I already googled and found something like this on SO (How do I change a value in django on button click in HTML?) but I am lacking knowledge of the concept presented in this thread. Unfortunately this was the only helpful information I could find.
How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button.
I somehome tried to adapt the code of the link:
views.py:
def ajax_change_status(request):
isReported = request.GET.get('isReported', False)
pk = request.GET.get('pk', False)
# first you get your Job model
job = Topic.objects.get(pk=pk)
try:
job.isReported = isReported
job.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)
xxx.html:
<form method="post" novalidate>
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button>
</form>
<script>
$("#change").on('click', function () {
var pk = '{{ topic.pk }}'
var isReported = 'True'
$.ajax({
url: '/ajax/change_status/',
data: {
'isReported': isReported
'pk': pk
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call success.");
// here you update the HTML to change the active to innactive
}else{
alert("ajax call not success.");
}
}
});
});
I am trying to understand the concept, but (obv.) it is not working.
POST /request/xxx-xxx-xxx-5622149-3/ HTTP/1.0" 200 5472
Related
i want to have simple functionality in my app. When user clicks on "show replies" button, div with class "replies" will show up, then button changes to "hide replies" and when click it again the div will disappear. I am close but the problem is: when I click on button first time (after reloading page), the button changes to "hide", data is not showing up. Until i click it second time it shows and then i have data and button "show replies". In other words: ajax call doesn't work on first time, data prints properly even with first click. Please help me to understand what is wrong.
ajax
$(document).ready(function () {
$(".showReplies").click(function () {
let id = $(this).attr('id');
$.ajax({
url: $(this).attr("data-href"),
type: 'get',
success: function (data) {
console.log(data);
$(`#${id}.replies`).html(data);
let text = $(`#${id}.showReplies`).text()
if (text == 'Show replies') {
text = 'Hide replies'
$(`#${id}.showReplies`).text(text)
} else {
text = 'Show replies'
$(`#${id}.showReplies`).text(text)
}
}
})
});
});
template
<button type="button" id="{{ comment.id }}" class="showReplies btn btn-link" data-href="{% url 'comment_replies' comment.id %}">Show replies</button>
<div class="replies" id="{{ comment.id }}" style="margin-left: 30px;">
{% include 'blog/comment_replies.html' %}
</div>
urls
path('comment_replies/<int:comment_id>/', comment_replies, name='comment_replies')
view
def comment_replies(request, comment_id):
comment = Comment.objects.get(id=comment_id)
replies = Reply.objects.filter(comment=comment)
context = {'replies': replies}
return render(request, 'blog/comment_replies.html', context)
Ok, #Swati found the solution:
$(document).ready(function () {
$(".showReplies").click(function () {
let id = $(this).attr('id');
$.ajax({
url: $(this).attr("data-href"),
type: 'get',
success: function (data) {
console.log(data);
$(`#${id}.replies`).html(data);
let text = $(`#${id}.showReplies`).text();
console.log(text);
if (text == 'Show replies') {
text = 'Hide';
$(`#${id}.showReplies`).text(text);
$(`#${id}.replies`).show();
} else {
text = 'Show replies';
$(`#${id}.showReplies`).text(text);
$(`#${id}.replies`).hide();
}
}
})
});
});
I had to add $(#${id}.replies).show();and $(#${id}.replies).hide();in if and else.
I'm trying to use Django Ajax to Modify user's avatar, but it doesn't work.There is no any error information, just doesn't work.
Here is my form in template:
<form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image_upload' %}" target='frameFile'>
<img id="avatarShow" src="{{ MEDIA_URL }}{{ request.user.image }}"/>
<input type="file" name="image" id="avatarUp" class=""/>
<button type="submit">Modify Avatar</button>
{% csrf_token %}
</form>
Here is my Ajax:
$("#jsAvatarForm").submit(function(){
var image = $("#avatarShow").val()
$.ajax({
cache: false,
type: "POST",
url:"{% url 'users:image_upload' %}",
data:{'user_pk':{{ user.pk }}, 'image':image},
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data) {
if(data.status == 'fail'){
if(data.msg == '用户未登录'){
window.location.href="login";
}else{
alert(data.msg)
}
}else if(data.status == 'success'){
window.location.reload();//refresh current page.
}
},
});
return false;
});
Here is views.py:
class UploadImageView(LoginRequiredMixin, View):
def post(self, request):
user_pk = request.POST.get("user_pk", 0)
image = request.FILES.get('image')
user_change = UserProfile()
user_change.id = user_pk
user_change.image = image
user_change.save
return HttpResponse('ok')
Actually I also have a forms.py but I don't know how to use it with ajax:
class UploadImageForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['image']
Here is my user model, note:I have rewrote my own USER:
class UserProfile(AbstractUser):
image = models.ImageField(upload_to="image/%Y/%m", default="image/default.png", max_length=100,verbose_name='头像')
class Meta:
verbose_name = "用户信息"
verbose_name_plural = verbose_name
def __str__(self):
return self.username
Any friend can help?Thank you so much!
Obviously You can send file such as image to django via js, depending of what you have posted in your question, I am showing you a way that you can proceed, there are lots of other ways to accomplish this fairly.
Feel free to comment, if anything is not working.
$("#jsAvatarForm").submit(function(){
var form = this;
// var image = $("#avatarShow").val() You can not retrieve the image like this
var formData = new FormData($(form)[0]);
// Everything inside the html form is serialized in the formData
// No need to add X-CSRFToken, {% csrf_token %} is inside the form
formData.append("NEW_KEY","NEW_VALUE"); # In case of further values
$.ajax({
url:$(form).attr('action'),
type:$(form).attr('method'),
data:formData,
processData: false,
contentType: false, //Don't set any content type header
success: function(){
// all your stuffs here
$('#avatarShow').attr('src',data.avatar_url)
},
error:function(){
alert("error");
}
});
return false;
});
Django
from django.http import JsonResponse
# codes here
user_change.image = image
user_change.save()
return JsonResponse({'avatar_url':user_change.image.url})
Note: Show the post view that rendering this template.
When I use ajax to submit a comment form in Django,the page will redirect to a blank page shows me the success data:
{"status":"success", "msg":"添加成功"}
,but not stay in current page.I want the page stay in current page and show me the new comment.
Here is my update_comment view:
def update_comment(request, news_pk):
news = get_object_or_404(News, id=news_pk)
comment_form = CommentForm(request.POST or None)
if request.method == 'POST' and comment_form.is_valid():
if not request.user.is_authenticated:
return render(request, 'login.html', {})
comments = comment_form.cleaned_data.get("comment")
news_comment = NewsComments(user=request.user, comments=comments, news=news)
news_comment.save()
# return redirect(reverse('news:news_detail', kwargs={'news_pk': news.id}))
return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
else:
return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')
Here is my ajax:
$(document).on('submit', 'comment_form', function(e){
e.preventDefault();
$.ajax({
cache: false,
type: "POST",
url:"{% url 'operation:update_comment' news.id %}",
data:{'news_pk':{{ news.id }}, 'comments':comments},
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data) {
if(data.status == 'fail'){
if(data.msg == '用户未登录'){
window.location.href="login";
}else{
alert(data.msg)
}
}else if(data.status == 'success'){
window.location.reload();//refresh current page.
}
},
});
});
Here is my form:
<form id="comment_form" action="{% url 'operation:update_comment' news.id %}" method="POST" >
{% csrf_token %}
<textarea id="comment_textarea"name="comment"></textarea>
<input type="submit" value="Submit"> </input>
</form>
Finally I made it!Thanks Lord!Very excited!
I have Three major issues in my previous code.
First:Since the ajax will post the news_pk to the view update_comment,so I don't need add news_pk in this view's url and template(in the url of <form> tag and the url in the ajax),so I removed them,or the data will still pass through Form but not ajax.
Second:My binding is incorrect,I have the click handler on the form it should be a submit handler. If I was binding it to a button then I'd use click a handler.Ajax not work in Django post
But for this part I'm still a some confused,between the button summit way and form submit way.
The third issue is I mistaked 'comments' and 'comment'.'comment' is the name attribute of <textarea> ,through which forms.py gets the data.
comments is defined by ajax through var comments = $("#js-pl-textarea").val(), so in the view I need use comments = request.POST.get("comments", "") but not comment,that's the reason why 'post failed'.
Following is my code.
Here is the ajax:
$("#comment_form").submit(function(){
var comments = $("#js-pl-textarea").val()
$.ajax({
cache: false,
type: "POST",
url:"{% url 'operation:update_comment' %}",
data:{'news_pk':{{ news.pk }}, 'comments':comments},
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data) {
if(data.status == 'fail'){
if(data.msg == '用户未登录'){
window.location.href="login";
}else{
alert(data.msg)
}
}else if(data.status == 'success'){
window.location.reload();//refresh current page.
}
},
});
return false;
});
Here is my udate_comment view:
#login_required
def update_comment(request):
news_pk = request.POST.get("news_pk", 0)
comments = request.POST.get("comments", "")
if int(news_pk) > 0 and comments:
news_comments = NewsComments()
news = News.objects.get(id=int(news_pk))
news_comments.news = news
news_comments.comments = comments
news_comments.user = request.user
news_comments.save()
return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
else:
return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')
Here is my form in template:
<form id="comment_form" action="{% url 'operation:update_comment'%}" method="POST" >
{% csrf_token %}
<textarea id="js-pl-textarea"name="comment"></textarea>
<input type="submit" value="Submit"> </input>
</form>
I really appreciate everyone's reply!With your reply I figured out these issue step by step!
I have something similar in my project. Its a script to like a song. I'm just gonna put the relevant codes here.
The ajax script. I put this script in a separate file named like_script.html. I call it in a template using django template include
<script>
$('#like').click(function(){
$.ajax({
type: "POST",
url: "{% url 'song:like_song' %}",
data: {'pk': $(this).attr('pk'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
alert(response.message);
},
error: function(rs, e) {
alert(rs.responseText);
}
});
})
</script>
The django view
import json
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
#login_required
#require_POST
def song_like_view(request):
if request.method == 'POST':
user = SiteUser.objects.get(user=request.user)
pk = request.POST.get('pk', None)
song = get_object_or_404(Song, pk=pk)
if song.likes.filter(pk=user.pk).exists():
song.likes.remove(user)
song.like_count = song.likes.count()
song.save(update_fields=['like_count'])
message = "You unstarred this song.\n {} now has {} stars".format(song.title, song.like_count)
else:
song.likes.add(user)
song.like_count = song.likes.count()
song.save(update_fields=['like_count'])
message = "You starred this song.\n {} now has {} stars".format(song.title, song.like_count)
context = {'message' : message}
return HttpResponse(json.dumps(context), content_type='application/json')
The url
urlpatterns = path("like/", views.song_like_view, name='like_song'),
The template where the script is called
<a class="btn btn-sm btn-primary" href="" id="like" name="{{ song.pk }}" value="Like"></i> Unstar</a>
{% include 'like_script.html' %}
Same button for like and unlike. I hope you can follow the logic to make yours right. Notice that in your view you don't need to include the pk. Just get it from the POST data pk = request.POST.get('pk', None)
I am using django-rest framework while sending put ajax request got error 403 forbidden.
user-details.html
<form action="{% url 'user-detail' pk=object.pk %}" id="use1">
{% csrf_token %}
{% for key,value in serializer.items %}
{{key}} <input value="{{value}}" type="text" class="form-control" /><br>
{% endfor %}
<button class="btn btn-warning edit_record" type="button" >Update</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
</form>
when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.
As far as I know we get this error when csrftoken is missing but I have csrf_token in my form.
$(".edit_record").on("click",function() {
var url = document.location.pathname
form = $(this).closest("form")[0],
formData = new FormData(form);
$.ajax({
type:'PUT',
url: url,
data: formData,
success: function (data) {
},
headers: {'X_METHODOVERRIDE': 'PUT'},
});
});
I used ModelViewset in views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserProfileSerializer
def update(self, request, *args, **kwargs):
import pdb;pdb.set_trace()
response = super(UserViewSet, self).update(request, *args, **kwargs)
success = True if response.status_code in [200,201] else False
return Response({'object':response.data, 'success':success})
def partial_update(self, request, *args, **kwargs):
import pdb;pdb.set_trace()
def destroy(self, request,*args, **kwargs):
response = super(UserViewSet, self).destroy(request, *args, **kwargs)
success = True if response.status_code == 204 else False
return Response({'data':success})
I think It is a Problem with Django Security and your Cookies. You need to configure your Middleware. Please take a look at this SO solution and this piece of Django Documentation.
What you could try is adding this to your Ajax Call and I would change the type to POST instead of PUT.
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
type: "POST",
.....
});
What worked for me is implementing this into my JS:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
try this,
$.ajax({
type:"DELETE",
data:{},
url:"{{ category_update }}",
beforeSend:function(xhr){
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},
success:function(data,textStatus){
location.replace(location.href);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
document.write(XMLHttpRequest.responseText);
}
});
the point is :
beforeSend:function(xhr){
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},
Thank you all for helping me but I got the solution by debug the dispatch method.Here I found that form data is missing that means there is invalid formdata in request.
There is no issue of csrf_token but issue in parameters which sent to ajax request.
In ajax currently i used -
form = $(this).closest("form")[0],
formData = new FormData(form);
and send this formData in request( still now i Don't know why it is not working here while i always used this thing in django).I just replace the above code with following code.
form = $(this).closest("form"),
formData = form.serialize()
I am not able to get the input text field data with id city_name from the form via jQuery-Ajax method.
The error that I keeps getting is "NetworkError: 403 FORBIDDEN - http://127.0.0.1:8000/dashboard".
I know how to get the data using hidden field type, but that option cannot be used here and moreover, getting data from hidden field is now an outdated method. So, how can I get data using Django-AjaxJquery method.
HTML
<form type = "POST">
{% csrf_token %}
<input type="text" placeholder = "Enter City Name" id = "city_name">
<input type="button" value = "On" id="on">
<input type="button" value = "Off" id="off">
</form>
JS File
$(function(){
$("#on").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "dashboard",
data : {
'city_name' : $("#city_name").val(),
},
});
});
});
View.py
#login_required
def dashboard(request):
ctx = {}
if request.is_ajax():
city_name = request.POST['city_name']
print city_name
return render_to_response('dashboard/dashboard.html',ctx, context_instance = RequestContext(request))
urls.py
urlpatterns = patterns('',
url(r'^dashboard$','apps.dashboard.views.dashboard', name = 'llumpps_dashboard'),
)
It is missing the CSRF token in the request.
You can either use #csrf_exempt decorator for your view like:
#login_required
#csrf_exempt
def dashboard(request):
...
Or send the token along with the request:
$.ajax({
type: "POST",
url: "dashboard",
data : {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val();
'city_name' : $("#city_name").val(),
},
complete: function () {
// do whatever here
}
});
Read more about CSRF and AJAX in Django here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
Hope it helps.