update django model using ajax

I have a collection of articles displayed in a table on my page, and I want to implement sorting functionality using AJAX by clicking on a button.

I am utilizing Dajaxice, which sends a request to ajax.py for the example1 method and receives JSON data as a response in the my_js_callback.

HTML:

<script>
function my_js_callback(data) {
    alert(data)
    $("#article_view_tbody").html("")
    for (i=0;i<data.length;i++)
         article=data[i]
     $("#article_view_tbody").append("<tr><td>" + data[i].title...) // here i need to set url for article edit
}
</script>
<button type="button" onclick="Dajaxice.content.example1(my_js_callback);">Click Me!</button>
<table>
<tbody id="article_view_tbody">
    {% for article in articles %}
        <tr>
            <a class="article_link" href="{% url article_detail article.id %}">
                    {{ article.title }}
        </a>
            </td>
         </tr> ...

ajax.py:

from django.utils import simplejson
from django.core import serializers
from dajaxice.decorators import dajaxice_register
from models import Article

def get_by_date_queryset():
      return Article.objects.all().order_by('created_on')

@dajaxice_register    
def example1(request):
    """ Handling sorting requests """
    queryset = get_by_date_queryset()
    json_serializer = serializers.get_serializer("json")()
    return json_serializer.serialize(queryset, ensure_ascii=False)

It is not possible to pass {% url %} tags directly into JavaScript. Is there a way to reload the tbody element with AJAX without appending new data with JavaScript?

Answer №1

Instead of just converting the queryset into JSON format for return, you can structure each element in a list with the following details:

    return [
        {
            'pk': article.pk,
            'title': article.title,
            'url': reverse('view_article', args=(article.pk,))  # Alternatively, use article.get_absolute_url()
        }
    for article in queryset]

To access the URL, title, etc., simply iterate through the returned JSON data using JavaScript and utilize articles[i].url within your for(var i = 0;... loop.

Update (regarding "bad way to hardcode"):

You can easily achieve this by:

serialized = json_serializer.serialize(queryset, ensure_ascii=False)
loaded = json.loads(serialized)
for row in loaded:
    row['url'] = reverse('view_article', args=(row['pk'],))
return json.dumps(loaded)

This approach also distinguishes the "fields" from the "url" for a more organized setup.

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

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

I am encountering an issue where the $scope.modal is returning as undefined when attempting to open an Ionic template modal. What

I am currently developing an Ionic application for the iPad. Within one of my templates, I have implemented a treeview with items. My goal is to open other templates modally when users click on these items. However, I encountered an error stating that $sco ...

encountering the issue "SymfonyComponentHttpKernelExceptionHttpException"

$.ajax({ method: 'post', url: '{{url("admin/append-course-pricebox-div")}}', data: {_token:{{csrf_token()}},count:boxCount,workshop_id:$("#workshop_id").val()}, ...

Converting an object with nested arrays into its original form (Ajax request using C#)

I am struggling with the deserialization of an object that has two properties. One property is a simple string, while the other property is an array of arrays, with each element in an array having a name and a value. The POST operation works fine until it ...

Using ajax to send multi-part form data as a JSON object

In the form below, there is an image field. I want to send all the data including the image through a JSON object. However, when trying to get the data using the code provided below, the logo field data is missing. How can I send the complete data at once? ...

Is it necessary for the keys in separate loops to be unique among siblings?

Does the use of key in loops create separate branches, or do they still need to be unique for the same parent? Take a look at this example: // This is obviously an error: <div> <div key="gimme-a-break" /> <div key="gim ...

Troubleshooting tip: Vue and Vuex - computed property will not update upon state change

I'm relatively new to Vue and Vuex, so please bear with me as I navigate through. My goal is to trigger the computed function versions() whenever there's a change in state.template, specifically when state.template.versions changes. This sectio ...

Tips for uploading files with AJAX while also including additional fields

As a beginner in ajax and .net MVC, I am facing an issue with uploading a file along with other form fields in my application. @using (Html.BeginForm("upload", "upload", FormMethod.Post, new { enctype = "mutipart/form-data" })) { < ...

Tips for dynamically populating a dropdown menu in Laravel with Ajax and JQuery

Hey pals, I'm encountering an issue with Ajax. Everything seems to be running smoothly when the page initially loads. However, once I hit the add button to insert a new row for a second entry, things start to go haywire. The functionality is perfect u ...

Use the jqwidgets jxGrid with the checkbox selection mode to enable row selection by checking for any clicks on the row

Currently, I am using a jqxGrid that contains checkboxes. I would like the ability for users to select a row by clicking on any part or column of the row, not just on the checkbox itself. Unfortunately, it seems this feature is not directly supported. Has ...

Tips for streamlining the JSON parse object prototype in JavaScript

I recently had a JavaScript object that was created without a prototype. let bar = Object.create(null); After reading and parsing a JSON file in Node.js, I reassigned the parsed data to bar. Here's how: fs.readFile('data.json', 'utf8 ...

Django is throwing an error because it cannot serialize an object of type 'datetime' into JSON format

I've encountered an issue while trying to store a date in my sessions. The error message I keep receiving is Object of type 'datetime' is not JSON serializable. Upon researching, I came across this useful resource in the Django documentation ...

Repeat a command in Discord.js indefinitely

Looking for help with this discord.js code I have. Currently, when someone runs the command "!cat", it sends a random image from r/cats. Here is the snippet: var Discord = require('discord.js'); var bot = new Discord.Client() randomPuppy = requir ...

The JOI validation process is failing to return all error messages, even though the "abort early" option

I have been encountering an issue while trying to validate my payload using a joi schema. Instead of returning the errors specified in the schema, only one error is being displayed. Even when I provide a payload with name as "int", it only shows one custom ...

Angular's ngOnDestroy lifecycle hook does not execute as expected after a button click event

When working on my HTML code, I encountered the following: <div class="form-group"> <button type="submit" value="submit" class="btn btn-secondary btn-float">Upload</butt ...

The Google Map information does not show up after I expand the accordion panel

Whenever I expand the navigation panel on my webpage, the Google map doesn't display anything and just appears as grey. It's only when I open the console that the map starts to appear. What changes do I need to make in my code so that the map sho ...

Utilize the power of dual API integration in a single request (multi-scope capability)

While there may not be a definitive answer to this question, I want to ensure that my situation cannot be resolved in any way. The crux of my application (and consequently the issue) is that each user possesses their own unique database and does not have ...

Resolving conflicts between class names for React-Icons in Typescript and Javascript (Answering my

After working with React in JavaScript, I made the switch to NextJs with TypeScript. I encountered an issue when trying to import react-icons such as BiUser. In React, adding a className to icons worked smoothly, but in TypeScript, it resulted in an error ...

Exploring the power of NativeScript and Angular 2's HTTP service

I am currently learning about native apps using JavaScript technologies and I am attempting to create a simple application utilizing the Pokemon API. Progress So Far I have developed a basic component that shows a list of pokemons retrieved from an HTTP ...

Unable to modify attribute within $templateCache through an AngularJS Directive

Here is my Directive code: module.directive('iconSwitcher', function() { return { restrict : 'A', link : function(scope, elem, attrs) { var currentState = true; elem.on('click', function() { ...