Struggling with transferring the vote variable to JavaScript without the use of forms, POST method, or the django-voting library

I've developed a streamlined system for entering and displaying short texts on a single web page. The text input is a simple input field with a GET in views. To enhance user interaction, I'm looking to implement a basic up or down voting system for the most recent entries. Some individuals online have suggested passing a variable to JavaScript as a first step.

Without utilizing forms or POST yet, as they seem excessive for my requirements, I'm seeking guidance on how to transfer my variable to JS effectively.

Below are snippets of code;

template

<script type="text/javascript"> 
{% for entry in voting_entry %}
    var votingEntry="{{entry.id}}"         
    {% endfor %}     
</script>

<script type="text/javascript" src="{{STATIC_URL}}vote.js"></script>

vote.js

$(document).ready(function() {

$("#votingEntry").bind("keypress", function(e) {

    if (e.keyCode == 38) {
        var vote = $("#votingEntry").val();     
        var args = {'vote':vote};           
        $.get("/vote/", args).done(function(data) {
        location.reload();  
      });
    }   
  });

views

def index(request):
  context = {
  'latest_entry_list': Entry.objects.order_by('-pub_date')[:10],
  'high_entry_list': Entry.objects.order_by('-score')[:10],
  'low_entry_list': Entry.objects.order_by('score')[:10],
  'voting_entry': Entry.objects.order_by('-pub_date')[:1],
  }
   return render(request, 'entries/index.html', context);

*snip*

def vote(request):
  voting_id = request.GET.get('vote')
  v = Entry.objects.get(pk='voting_id')
  v.score +=1
  v.save()       
  return HttpResponse('votedone')

Answer №1

It seems a bit unclear what your intentions are with the code snippet provided. You seem to be repeatedly assigning a string value, containing an ID from a list, to the variable votingEntry. Since you are reassigning the same variable each time, it will ultimately hold only the last value from the list.

Furthermore, if you intend to declare a global variable outside of a function in JavaScript, you should use the var keyword.

However, it is puzzling as to why you are performing these actions, especially since you do not make any further use of the votingEntry variable in your JavaScript code. Providing more context on your desired outcome would be helpful for better understanding.

Answer №2

Implemented a straightforward form in the template to handle sorting. The submit buttons trigger a views.vote function through a URL, where the vote (up or down) is detected and saved for the corresponding entry ID. This is achieved by using POST.get on the hidden name within the template form.

To keep everything on one page and refresh the index, a redirect is utilized.

Template

<ul>
{% for entry in voting_entry_list %}
    <li><a href="/entries/{{ entry.id }}/">{{ entry.text }}{{ entry.score }}</a></li>
    <li><form method="POST" action="/vote/" >
    {% csrf_token %}
      <input type="hidden" name="voteid" value="{{ entry.id }}" />
      <input type="submit" name='voteup' value="Up" />
      <input type="submit" name='votedown' value="Down" />
    </form><li>  
{% endfor %}  
</ul> 

URLs

urlpatterns = patterns('',
  url(r'^admin/', include(admin.site.urls)),
  url(r'^index/$', 'entries.views.index'),
  url(r'^add/$', 'entries.views.add'),
  url(r'^vote/$', 'entries.views.vote')
)

Views

@csrf_protect  
def vote(request):
 voting_id = request.POST.get('voteid',None)
 if request.method=='POST':
   if 'voteup' in request.POST:
     v = Entry.objects.get(pk=voting_id)
     v.score +=1
     v.save()
   if 'votedown' in request.POST:
     v = Entry.objects.get(pk=voting_id)
     v.score -=1
     v.save()
 else:
    pass
 return HttpResponseRedirect('/index')

Resolved a final issue by removing quotes from - pk=voting_id - to avoid an "invalid literal for int() with base 10" error.

For those seeking a basic approach to implementing these systems outside of traditional Django polls tutorials, this method provides a different perspective. Navigating through various methods such as JSON, JS, POST, forms, regex, URLs, etc., can be challenging, so I've shared my implementation utilizing snippets from multiple SO questions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble executing javascript with Ext.Ajax in Sencha-Touch2?

Currently, I am utilizing htmlPanel.js in Sencha-Touch as discussed in the Forum here to exhibit local HTML content. Even though I can load the HTML content with standard HTML tags, I'm facing issues with loading JavaScript. Here's the snippet o ...

React Bootstrap encountered rendering issues

Recently, I decided to delve into the world of React Bootstrap and started my learning journey. To get started, I followed some tutorials on <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="vi ...

"Enhancing Functionality: A Detailed Guide on Callback Functions in Express

Currently, I am expanding my coding skills by learning express/Node, transitioning from C and PHP/MySQL. The MDN tutorial on express has been incredibly helpful in my learning journey, making everything straightforward. Thanks to the Mozilla teaching team, ...

Save the selected form data and store it as a hidden field in the form

There is a table available for users to select items from: <form action="submitSelection.php" method="post" role="form"> <table class="table table-condensed table-striped table-bordered"> <thead> <th scope="col">Code ...

Is it achievable to prioritize specific nodes being in closer proximity to each other in a Force Directed graph visualization?

In the midst of my current project, I am diving into the intricacies of measuring the "closeness" between an individual and their Twitter friends and followers. This closeness is determined by how often the individual mentions others or is mentioned by oth ...

Evaluate the Javascript string and save the output

My challenge involves receiving JavaScript as a string that needs to be executed and compared to a specific output. Currently, I am utilizing the eval() function for this task, but I am open to alternatives. The execution takes place on the client side wit ...

Creating a submit button with Django and Ajax: a step-by-step guide

I am completely new to using jquery and Ajax, and I've been struggling with submitting data via ajax as advised. I tried following examples from How do I POST with jQuery/Ajax in Django? and Django jQuery post request, but unfortunately, they didn&apo ...

Alert: Notification Failure

Is it possible to generate customized errors in the admin platform in this manner?: Typically, I trigger the error using: raise forms.ValidationError('error') However, this display the debug error screen. ...

Adding a delay for the removal of a class from a button in JavaScript after the class has been added

Apologies if this is a basic question, but despite my attempts to find solutions on StackOverflow, I am still struggling with implementing the desired functionality on my website project. I am developing a website and I want the download button to change ...

Troubleshooting: How to Fix Missing Sum Display in HTML Input Fields

I am new to the world of website programming and I am currently working on creating a basic sum equation using two input fields from the client-side. <!DOCTYPE html> <html> <head> </head> ...

Refresh the information on the page by loading data from the log file using AJAX

I am currently running a shell script in the background and directing the output to a log file using PHP. I'd like to showcase the content of this log file on the webpage, which I've managed to achieve with the following code snippet. <?php ...

What is the best way to adjust the width of floating divs to completely fill the space they occupy?

On the first picture, there are six equal divs displayed. As the screen size increases, the width of the divs also grows to fill up their space, like a table cell or another div. If there is enough space in the first row to accommodate the fourth div, it s ...

JavaScript and HTTP Post parameters: Consider using optional additional parameters

Managing a filtration function, I have an array of checkboxes and dropdowns. Users can select multiple checkboxes and dropdown values before clicking on the "Filter Now" button. Upon clicking the button, a POST request is triggered to my API, passing alon ...

Can Django capture and store the name of the active user's logged-in browser in the database?

In Django, we already have session details stored in django_session and last_login in the auth_user table. However, I am interested in storing the browser name when a user logs in using their browser in the database. Currently, I can retrieve the browser ...

Showing Stationary Pictures at Full Size in OpenLayers

I am trying to showcase static images as maps using a StaticImage layer in ol3, with the image size set at 100% in pixels. However, I am facing difficulty in ensuring that the displayed images are always the correct size based on the extent and zoom variab ...

Refresh client web pages with JSON data without using eval

I am currently working as a consultant on a web application that functions as a single page app. The main purpose of the app is to constantly fetch new json data in the background (approximately every minute) and then display it on the screen. Our clients ...

Exploring the process of iterating through Django form errors post-receiving them in JSON format via AJAX

Everything seems to be working fine with my signup form, as it saves users correctly without any errors. However, I am facing an issue when trying to display errors related to form field validation. Despite retrieving the errors using form.errors.as_json, ...

The ambiguity surrounding the timing of decorator invocation in TypeScript

My understanding was that decorators in TypeScript are invoked after the constructor of a class. However, I recently learned otherwise. For example, the primary response on this thread suggests that Decorators are called when the class is declared—not wh ...

The RedirectToLocal function is not functioning correctly

I am encountering an issue with my login page while using Angular in a View. After the "RedirectToLocal" command is executed, I can see that it hits my Home Controller and returns the Index view successfully. However, the browser does not actually navigate ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...