Calling Django `reverse` in client-side Javascript

前端 未结 10 487
无人共我
无人共我 2020-12-13 02:22

I\'m using Django on Appengine. I\'m using the django reverse() function everywhere, keeping everything as DRY as possible.

However, I\'m having trouble

10条回答
  •  有刺的猬
    2020-12-13 02:56

    One of the solutions I came with is to generate urls on backend and pass them to browser somehow.

    It may not be suitable in every case, but I have a table (populated with AJAX) and clicking on a row should take the user to the single entry from this table.

    (I am using django-restframework and Datatables).

    Each entry from AJAX has the url attached:

    class MyObjectSerializer(serializers.ModelSerializer):
        url = SerializerMethodField()
        # other elements
    
        def get_url(self, obj):
           return reverse("get_my_object", args=(obj.id,))
    

    on loading ajax each url is attached as data attribute to row:

    var table = $('#my-table').DataTable({
       createdRow: function ( row, data, index ) {
          $(row).data("url", data["url"])
       }
    });
    

    and on click we use this data attribute for url:

    table.on( 'click', 'tbody tr', function () {
      window.location.href = $(this).data("url");
    } );
    

提交回复
热议问题