Not entering Else Statement from user.is_authenticated - django

In the castmascotvote view, everything is working when I'm authenticated, but not working otherwise. I have a print('entering not authenticated') right when it enters the else statement if the user isn't authenticated, but it never enters it, i'm boggled. I don't understand at all why it's not working. does anyone have any idea where I should start looking?
error message
The view didn't return an HttpResponse object. It returned None instead.
But I clearly have a HttpResponse object!
.html
<form class="mascotvoteform" action="{% url 'castmascotvote' mascot.id %}" id="{{mascot.id}}">
<div class="p-0"><h4>{{ mascot.name }} </h4> <p> by {{ mascot.author }} </p></div>
<div class="p-0"><img class="img-thumbnail" src="{{ mascot.image.url }}" style="width:250px;"></div>
<div class="row p-3">
{% if mascot.total_votes is 0 %}
<div class="col"><h5 id="mascotvotes{{mascot.id}}">0</h5></div>
<button class="col btn btn-primary" type="submit" id="castmascotvote{{mascot.id}}">Vote</button>
{% else %}
<div class="p-0 col"><h5 id="mascotvotes{{mascot.id}}">{{ mascot.total_votes }}</h5></div>
<button class="col btn btn-primary" type="submit" id="castmascotvote{{mascot.id}}">Vote</button>
{% endif %}
</div>
</form>
.script
$( document ).ready(function() {
$(".mascotvoteform").submit(function(e) {
{% if user.is_authenticated %}
e.preventDefault()
{% endif %}
let mascot_id = $(this).attr("id");
let url = $(this).attr('action');
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'mascot_id': mascot_id,
},
success: function(response) {
console.log('success', response)
$(`#mascotvotes${mascot_id}`).text(`${response['total_votes']}`)
};
},
error: function(response) {
console.log('error', response)
}
});
})
.views
def castmascotvote(request, mascot_id):
mascot = PoopMascot.objects.get(id=mascot_id)
user = request.user
if request.method == 'POST':
if user.is_authenticated:
if user in mascot.votes.all():
mascot.votes.remove(user)
else:
mascot.votes.add(user)
total_votes = mascot.total_votes()
data = { "total_votes":total_votes }
return JsonResponse(data, safe=False)
else:
print('entering user not authenticated')
messages.error(request, 'Please sign in to vote Poop Hero!')
return render(HttpResponseRedirect(reverse('user_login')))
else:
pass

Related

Why Is Ajax Creating a New Comment When I'm Trying To Edit An Existing One?

I am trying to do a Django Blog in Class Based Views. They're proving very difficult to me anyway. I feel like I'm pretty close...I suspect it's creating a new one because I'm combining DetailView and trying to include an UpdateView in my page. I'm overriding POST on the DetailView...and perhaps that's why when I try to do my Update of the comment the overriden Post on DetailView is overriding that action?
Here's my code....
HTML...
<!DOCTYPE html>
<form method='POST' class="comment-form">
{% csrf_token %}
<div class="spacer284">
{{ form.comment }}
</div>
<button class="button7" type="submit">Submit</button>
</form>
<div class="spacer285">
{% include 'suggestion_comments.html' %}
</div>
</div>
{% endblock %}
Note that I'm doing an include so that I can loop through the comments more easily...
Here's the include template...
{% if suggestion_comments %}
<h2>Comments</h2>
{% for comment in object.suggestion_comments.all %}
<div class="spacer291">
<p>{{ comment.author }} {{ comment.created_on }}</p>
<p class="spacer290">{{ comment.comment }}</p>
<div class="spacer289">
<div class="upvote-comment-count">{{ comment.total_comment_upvotes }}</div>
<div class="hide-delete">
<button type="button" class="button6" data-href="{% url 'Suggestions:suggestion_comment_like' comment.id %}">Like</button>
</div>
<div class="hide-delete">
<button type="button" class="button2" data-href="">Reply</button>
</div>
{% if comment.author == request.user %}
<button type="button" class="button4" id="{{ comment.id }}" pk="{{ object.pk }}" href="{% url 'Suggestions:suggestion_comment_edit' object.pk comment.id %}">Edit</button>
<div class="spacer159" id="hide_payment" style="display:none;">
<input name="comment" id="commentInput" value="{{ comment.comment }}" class="name"/>
<button class="button7">Submit</button>
</div>
<div class="hide-delete">
{% if user.userprofile.eDirector_queue_delete_confirm == "Yes" %}
<button type="button" class="button5" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button>
{% else %}
<button type="button" class="button3" data-href="{% url 'Suggestions:suggestion_delete' comment.id %}">Delete</button>
{% endif %}
</div>
{% endif %}
</div>
</div>
{% endfor %}
{% else %}
<h2>No Comments Yet</h2>
{% endif %}
I'm attempting to use AJAX to do a replace...
$(document).on('submit', '.comment-form', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
type: "POST",
url: $this.data("href"),
data: $this.serialize(),
dataType: "json",
csrfmiddlewaretoken: "{{ csrf_token }}",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(response){
console.log("so far");
$('.spacer285').html(response['form']);
$(".comment-form")[0].reset();
$('.spacer288').empty('spacer288');
},
error: function (request, status, error) {
console.log(request.responseText);
showAjaxFormErrors(JSON.parse(request.responseText));
},
});
});
$(document).on('click', '.button7', function(e) {
e.preventDefault();
console.log("working123");
var $this = $(this);
var comment = $('#commentInput').val();
console.log(comment);
$.ajax({
type: "POST",
url: $this.data("href"),
data: { comment: comment},
csrfmiddlewaretoken: "{{ csrf_token }}",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
success: function(data){
console.log(data);
$('.comment-form1').html(data);
},
});
});
My DetailView...
class SuggestionDetailView(LoginRequiredMixin,DetailView):
model = Suggestion
context_object_name = 'suggestion_detail'
template_name = 'suggestion_detail.html'
def get_context_data(self, **kwargs):
context = super(SuggestionDetailView, self).get_context_data(**kwargs)
attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all()
form = SuggestionCommentForm()
suggestion_comments = SuggestionComment.objects.filter(suggestion_id=self.object.pk).order_by('-created_on').all()
context['attachments'] = attachments
context['form'] = form
context['suggestion_comments'] = suggestion_comments
return context
def post(self, request, *args, **kwargs):
form = SuggestionCommentForm(request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.author = request.user
new_comment.suggestion = self.get_object()
new_comment.save()
self.object = self.get_object()
context = self.get_context_data(object=self.object)
html = render_to_string('suggestion_comments.html', context, request=self.request)
return JsonResponse({'form': html})
else:
form_errors = form.errors.as_json()
response = HttpResponse(form_errors, status=400)
response['content_type'] = 'application/json'
return response
MyCommentUpdateView...
class SuggestionCommentUpdateView(LoginRequiredMixin, UpdateView):
model = SuggestionComment
fields = ["comment"]
def form_valid(self, form):
form.instance.suggestion_id = self.kwargs["pk"]
return super().form_valid(form)
And my URLs...
path("a7900f81-b66a-41ea-afc2-d7735e6d4824/suggestion_detail/<uuid:pk>/suggestion_comment_edit/<int:id>",views.SuggestionCommentUpdateView.as_view(), name='suggestion_comment_edit'),
path("a7900f81-b66a-41ea-afc2-d7735e6d4824/suggestion_detail/<uuid:pk>/",views.SuggestionDetailView.as_view(), name='suggestion_detail'),
This is all almost working....My issue is when I click on the edit button and attempt to edit the comment....it works...and updates the database...but it's adding a new updated comment instead of just editing the existing comment. Thanks in advance for any thoughts on what I might be doing wrong.

asynchronus form submission django

I'm using ajax to submit a form, and it's working. But it's not working asynchronously. When I'm trying to upload files it uploaded successfully and then the page loads again. I want it to make asynchronously. In addition, I want to make a progress bar too. But things not working as I expected.
my forms.py
from django import forms
from .models import Comment
from .models import post
class UploadForm(forms.ModelForm):
class Meta:
model = post
fields = ('image', 'video', 'content',)
my views.py
def django_image_and_file_upload_ajax(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.instance.author = request.user
form.save()
return JsonResponse({'error': False, 'message': 'Uploaded Successfully'})
else:
return JsonResponse({'error': True, 'errors': form.errors})
else:
form = UploadForm()
return render(request, 'blog/upload.html', {'form': form})
and my upload.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<main>
<div class="container">
<div class="row">
<div class="col-md-8 my-5">
<div class="content-section" style="padding:10px 20px">
<form
enctype="multipart/form-data"
id="id_ajax_upload_form" method="POST"
novalidate="">
<fieldset class="form-group">
{% csrf_token %}
<legend class="border-bottom mb-4"><i class="fas fa-feather-alt text-muted mr-2"></i>Create a post</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<input type="submit" />
</div>
</form>
</div>
</div>
</div>
</div>
</main>
{% endblock content %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
// form upload
$('#id_ajax_upload_form').submit(function(e){
e.preventDefault();
$form = $(this)
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (response) {
$('.error').remove();
console.log(response)
if(response.error){
$.each(response.errors, function(name, error){
error = '<small class="text-muted error">' + error + '</small>'
$form.find('[name=' + name + ']').after(error);
})
}
else{
alert(response.message)
window.location = ""
}
},
cache: false,
contentType: false,
processData: false
});
});
// end
where i get wrong?
Ok, Got it! But anyone know about how to add a progressbar will be helpful.

Post method in django using ajax

I have a form that I am trying to implement with Ajax, after inputing some content on the textbox, when I click on the sumbit button using my mouse, everything works fine (page didnt refresh, data posted on database, and new data displayed on the page). But when I try to submit data by pressing enter, the page is displaying only the serialized data from my form (nothing more, html file do not work)and it says in the console:
Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8000/try/".
current page looks exactly like this after pressing enter button(nothing more):
{"task": {"id": 52, "todo": "wws", "author": 1, "completed": false}}
these are the data that came from my form.
this is my views.py
class TodoList(View):
def get(self, request):
todo_list = ToDo.objects.filter(author_id=request.user.id)
form = AddTodo()
context = {
'todo_list': todo_list,
'form': form,
}
return render(request, 'trylangto/try.html', context)
def post(self, request):
form = AddTodo(request.POST)
if form.is_valid():
form.instance.author_id = request.user.id
new_form = form.save()
return JsonResponse({'task': model_to_dict(new_form)}, status=200)
else:
return redirect('trylang:todo-list')
return redirect('trylang:todo-list')
this is my main.js:
$(document).ready(function(){
$("#createbutton").click(function(){
var formdata = $("#addtodoform").serialize();
$.ajax({
url: $("#addtodoform").data('url'),
data: formdata,
type: 'post',
success: function(response){
$("#tasklist").append('<div class="card mb-1" ><div class="card-body">'+ response.task.todo +'<button type="button" class="close"><span aria-hidden="true">×</span></button></div></div>')
}
});
});
});
and here is my template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
{% if user.is_authenticated %}
<div class="media content-section">
<form class="media-body pt-3" method="POST" id="addtodoform" data-url="{% url 'trylang:todo-list' %}">
{% csrf_token %}
<legend><h5>add new tasks</h5></legend>
<fieldset class="form-group ">
{{ form|crispy}}
</fieldset>
<button class="btn btn-outline-info float-right" type="button" id="createbutton">add</button>
</form>
</div>
{% endif %}
<div id="tasklist">
{% for task in todo_list %}
<div class="card mb-1" >
<div class="card-body">
{{task.todo}}
<button type="button" class="close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
UPDATE: I am including my models.py just in case
class ToDo(models.Model):
todo = models.CharField(max_length=500)
date_posted = models.DateTimeField(default=timezone.now, editable=False)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
completed = models.BooleanField(default=False)
this is what I get on the console when I use console.log(formdata):
csrfmiddlewaretoken=N91OUGSd6kBFkB1E2DMZuMW6qJD7cc3frPprwGMLTuupcg6PKYtt44jA4z5Lx6xX&todo=this%20is%20the%20content%20of%20my%20textbox
You don't need model_to_dict. So, try:
if form.is_valid():
form.instance.author_id = request.user.id
new_form = form.save()
return JsonResponse({'task': new_form}, status=200)
else:
return redirect('trylang:todo-list')
return redirect('trylang:todo-list')
EDIT
You are submitting the form not through ajax. When you click button it was submitting the form. So, e.preventDefault() should do the job.
$(document).ready(function(){
$("#createbutton").click(function(e){
e.preventDefault(); <--- You were missing this
var formdata = $("#addtodoform").serialize();
$.ajax({
url: $("#addtodoform").data('url'),
data: formdata,
type: 'post',
success: function(response){
$("#tasklist").append('<div class="card mb-1" ><div class="card-body">'+ response.task.todo +'<button type="button" class="close"><span aria-hidden="true">×</span></button></div></div>')
}
});
});
});

Django Endlesss pagination breaks buttons genereated by endlesss pagination

I have endless pagination working on my site for posts.
Each post has a like and dislike button which works using ajax.
The first set of posts have working buttons but all posts delivered with pagination don't have working buttons. When clicking the buttons they don't even run the ajax to send a query to my views.py file but the first set of posts have working ones.
urls.py
path("likepost/", user_views.like_post_view, name='like_post'),
path("dislikepost/", user_views.dislike_post_view, name='dislike_post'),
views.py file
sort = request.GET.get("sort")
if sort=="newest":
posts = Post.objects.filter(deleted=False).order_by('-date_posted')
sort_type = "newest"
if sort=="oldest":
posts = Post.objects.filter(deleted=False).order_by('date_posted')
sort_type = "oldest"
if sort=="top-alltime":
posts = Post.objects.filter(deleted=False).annotate(like_count=(Count('like_post')-Count("dislike_post"))).order_by('-like_count')
sort_type = "top-alltime"
if sort==None or sort=="top-today":
today = datetime.now().date()
today_start = datetime.combine(today, time())
posts = Post.objects.filter(deleted=False, date_posted__gte=today_start).annotate(like_count=(Count('like_post')-Count("dislike_post"))).order_by('-like_count')
sort_type = "top-today"
if sort=="top-week":
current_week = date.today().isocalendar()[1]
posts = Post.objects.filter(deleted=False, date_posted__week=current_week).annotate(like_count=(Count('like_post')-Count("dislike_post"))).order_by('-like_count')
sort_type = "top-week"
page = request.GET.get('page', 1)
paginator = Paginator(posts, 4)
trending_tags = Post.tags.most_common()[:5]
try:
posts_given = paginator.page(page)
except PageNotAnInteger:
posts_given = paginator.page(1)
except EmptyPage:
posts_given = paginator.page(paginator.num_pages)
context = {
"trending_tags": trending_tags,
"posts_given": posts_given,
"sort": sort_type
}
return render(request, "users/index.html", context)
#login_required
#require_GET
def like_post_view(request):
print("LIKE REQUESTED!!!!!!!!!!!!!")
if request.method == 'GET':
user = request.user
user = User.objects.get(username=user)
post_id = request.GET.get('post_id', None)
post = Post.objects.get(id=post_id)
if like_post.objects.filter(user=user, post=post).exists():
# user has already liked this post
# remove like/user
like_post.objects.filter(user=user, post=post).delete()
#return -1
return HttpResponse(-1)
else:
# add a new like for the post
like_post.objects.create(post=post, user=user)
if dislike_post.objects.filter(user=user, post=post).exists():
dislike_post.objects.filter(user=user, post=post).delete()
return HttpResponse(+2)
return HttpResponse(+1)
#login_required
#require_GET
def dislike_post_view(request):
print("DISLIKE REQUESTED!!!!!!!!!!!!!")
if request.method == 'GET':
user = request.user
user = User.objects.get(username=user)
post_id = request.GET.get('post_id', None)
post = Post.objects.get(id=post_id)
if dislike_post.objects.filter(user=user, post=post).exists():
# user has already disliked this post
# remove dislike/user
dislike_post.objects.filter(user=user, post=post).delete()
return HttpResponse(+1)
else:
# add a new dislike for the post
dislike_post.objects.create(post=post, user=user)
if like_post.objects.filter(user=user, post=post).exists():
like_post.objects.filter(user=user, post=post).delete()
return HttpResponse(-2)
return HttpResponse(-1)
template
{% load static %}
{% block content %}
<h1>Homepage</h1>
<div class="infinite-container" id="infinite-container" style="max-width:700px;width:100%;margin-left:auto;margin-right:auto;">
<form action="/action_page.php">
{% csrf_token %}
<div style="display:inline-block;">
<h5 style="margin-left:10px;">Sort by</h5>
<select name="sort" class="sort_by" id="sort_by" style="margin-left:10px;">
<option value="newest">Newest</option>
<option value="top-today" selected="selected">Top Today</option>
<option value="top-week">Top This Week</option>
<option value="top-alltime">Top All Time</option>
<option value="oldest">Oldest</option>
</select>
</div>
</form>
{% for post in posts_given %}
<div class="post infinite-item" style="background-color:#494a4d;border-radius: 8px; color: white;padding:10px;margin:10px;">
<h2>{{ post.title }}<h2>
<hr>
<img src="/uploads/{{ post.image }}" alt="{{ post.image }}" style="max-width:100%; max-height:500px;">
<hr>
<div class="row-post">
<div class="column-post-left">
<h4 style="text-align: left;">by {{ post.user.username }} | {{ post.date_posted | timesince }} ago {% if request.user.is_authenticated and post.user == request.user %} | edit{% else %} | report{% endif %}</h4>
<h5 style="word-wrap: break-word;word-break: break-word;">{% for tag in post.tags.all %} #{{ tag }}{% endfor %}</h5>
<h5>{{ post.comment_count }} comments</h5>
</div>
<div class="column-post-right">
<input src="{% static "memeplaza/rocket_white.png" %}" type="image" style="max-width:50px;max-height:50px;" class="like" name="{{ post.id }}" value="Like"/>
<p style="font-size:22px;" id="{{ post.id }}">{{ post.like_count }}</p>
<input src="{% static "memeplaza/flash_white.png" %}" style="max-width:50px;max-height:50px;" type="image" class="dislike" name="{{ post.id }}" value="Dislike" />
</div>
</div>
</div>
{% endfor %}
</div>
{% if posts_given.has_next %}
<a class="infinite-more-link" href="?sort={{ sort }}&page={{ posts_given.next_page_number }}"></a>
{% endif %}
<script>
var infinite = new Waypoint.Infinite({element: $('.infinite-container')[0]});
$('.sort_by').change(function(){
var sort_type = $('#sort_by :selected').val();
window.location = "/?sort="+sort_type;
})
$('.like').click(function(){
var id = $(this).attr('name');
console.log("Like button pressed!");
$.ajax({
type: "GET",
url: "{% url 'like_post' %}",
data: {'post_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
var score = $("#" + id).text();
score = score.split(" ")[0];
score = parseInt(score) + parseInt(response);
$("#" + id).text(score);
}
});
})
$('.dislike').click(function(){
var id = $(this).attr('name');
console.log("disLike button pressed!");
$.ajax({
type: "GET",
url: "{% url 'dislike_post' %}",
data: {'post_id': $(this).attr('name'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
var score = $("#" + id).text();
score = score.split(" ")[0];
score = parseInt(score) + parseInt(response);
$("#" + id).text(score);
}
});
})
</script>
{% if sort is not empty %}
<script>
$(document).ready(function(){
$("#sort_by").val("{{ sort }}");
});
</script>
{% endif %}
{% endblock content %}```
You should use $('selector').on for binding events to elements that do not exist yet
$('#infinite-container').on('click', '.like', function() {
...
})
$('#infinite-container').on('click', '.dislike', function() {
...
})
Using $('.like').click will only bind the event handler to elements that currently exist on the page

How to disable button when required field is empty

Hello i need your help i need to disable this button send when the required field are empty. I am a beginner using django and i don't know how to resolve it. Please i need your help .. i lost my time trying to find a solution.
Views.py:
def contact(request):
form = FeedbackForm(request.POST or None)
if form.is_valid():
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.urlencode(values).encode()
req = urllib2.Request(url, data=data)
response = urllib2.urlopen(req)
result = json.loads(response.read().decode())
''' End reCAPTCHA validation '''
if result['success']:
form.save()
message = u'You have feedback\nName: %s\nEmail: %s\nPhone: %s\nCountry: %s\nFeedback:\n%s' % (
form.cleaned_data['name'],
form.cleaned_data['email'],
form.cleaned_data['phone'],
form.cleaned_data['country'],
form.cleaned_data['feedback'])
try:
send_mail('NEW FEEDBACK', message, '', settings.DEFAULT_FROM_EMAIL) # to admin
send_mail('THANK YOU for contacting us', 'We will be back to you promptly.', '', [form.cleaned_data['email'],]) # to user
messages.info(request, 'SUCCESS! Your message has been sent!')
form = FeedbackForm()
except:
messages.info(request, 'Sorry, can\'t send feedback right now.')
else:
messages.error(request, 'Invalid reCAPTCHA. Please try again.')
return render(request, 'contact.html', {'active_page':'contact','form': form,})
Contact.html:
<html>
<div class="col-md-6">
<form role="form" class="form" method="post">
{% csrf_token %}
{% for field in form %}
<label for="{{ field.label }}">{{ field.label_tag }}
{% if field.field.required %}<span class="red">*</span>{% endif %}</label>{{ field.errors }}{{ field }}
{% endfor %}
<p><span class="redText">*</span> Indicates a required field</p>
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey=""></div>
<input type="submit" value="Send" class="btn btn-lg">
</form>
The best way to do this would be to use JavaScript and jQuery.
In this example, when you click your button you can make sure the form is valid before it submits.
$(".validate").on("click", function () {
if (!valid()) {
alert("You are missing required fields.");
return false;
}
else {
return confirm("This will submit the form. Are you sure?");
}
});
function valid() {
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" class="validate" value="Send" class="btn btn-lg">
This code adds a class to your button. The jQuery listens for the click, then makes a JavaScript function that would check if it is valid. If it is not, it displays an alert. If it is, it displays a confirm message.
There are many other ways to do this with JS though.