Passing dynamic javascript variable as url in template

走远了吗. 提交于 2020-06-29 03:41:15

问题


I am trying to create a dynamic url in javascript to pass to my html template.

In my js, I've got:

// dynamic url to edit flashcard
function createDynamicURL()
{
    //The variable to be returned
    var URL;

    //The variables containing the respective IDs
    var cardID= cards.cards[current_card].id   //this is defined earlier

    //Forming the variable to return
    URL-="study/[1-9][0-9]/";
    URL+="card-edit/";
    URL+=cardID;

    return URL;
}

And in my template I have:

<a id="edit-button" class="btn btn-default btn-warning" href="javascript:window.location=createDynamicURL();"  >Edit</a>

My urls.py:

app_name = 'flash'

urlpatterns = [
    re_path(r'^study/(?P<deck_id>[0-9]+)/$', views.study, name='study'),
    re_path(r'^study/(?P<deck_id>[0-9]+)/get_cards/$', views.get_cards, name='get-cards'),
    path("decks/",views.DeckList.as_view(),name="deck-list"),
    path("decks/<int:pk>/",views.DeckDetail.as_view(),name="deck-detail"),
    path("cards/<int:pk>/", views.CardList.as_view(), name="flash-list"),
    path("card-edit/<int:pk>/",views.CardEdit.as_view(),name="flash-edit"),
    path("card-detail/<int:pk>/",views.CardDetail.as_view(),name="flash-detail"),
    path("edit/<int:pk>/",views.DeckUpdate.as_view(),name="edit"),
    path("",views.home,name="home"),

]

The url I get when I click: http://127.0.0.1:8000/%2Fflash/study/33/NaNcard-edit/51

The the correct url would have been: http://127.0.0.1:8000/%2Fflash/card-edit/51/

So at least it is giving me the correct id. But why is it giving me NaN, and how do I get rid of the study/33? Note the 33 will not always be 33, and I don't have access to that id here, so I want it to be just any 2-digit number.

I don't have a lot of experience with javascript, so sorry for the basic question. Any advice would be greatly appreciated!

Study views:

@login_required
@ensure_csrf_cookie
def study(request, deck_id):
    """
    Study cards page (JS driven)
    """
    if request.method == 'GET':
        return render(request, 'flash/study.html')


@login_required
@csrf_exempt
def get_cards(request, deck_id):
    """
    Get cards to study (ajax)
    """

    if request.method == 'GET':
        cards = Flashcard.objects.filter(owner=request.user, deck=deck_id,
                                         next_due_date__lte=timezone.now())
        count = len(cards)
        data = {'count': count, 'cards': []}

        num = count if count < CARD_LIMIT else CARD_LIMIT
        if num:
            # generate list of random indexes
            idx = random.sample(range(count), num)
            for i in idx:
                card = cards[i]
                question = '<p>'+'</p><p>'.join(card.question.split('\r\n'))+'</p>'
                answer = '<p>'+'</p><p>'.join(card.answer.split('\r\n'))+'</p>'
                data['cards'].append({'id': card.pk, 'question': question,
                                     'answer': answer})

        return JsonResponse(data)
    else:
        data = json.loads(str(request.body, 'utf-8'))
        for res in data:
            card = Flashcard.objects.get(owner=request.user, pk=res['id'])
            card.save(rating=res['result'])

        return JsonResponse({'status': 'OK'})

回答1:


If you have the card object in your template, Try this :

<a id="edit-button" class="btn btn-default btn-warning" href="{% url 'flash-edit' card.id %}"  >Edit</a>


来源:https://stackoverflow.com/questions/62367518/passing-dynamic-javascript-variable-as-url-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!