0

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'})
3
  • You're initializing an empty string URL then calling "URL-="study/[1-9][0-9]/";", which doesn't make sense since URL is empty at that point, so that's probably what is causing the NaN part of the string. What url do you get if you comment that line? Commented Jun 14, 2020 at 3:11
  • @ketcham If I remove "URL-="study/[1-9][0-9]/";", I get: 127.0.0.1:8000//flash/study/33/undefinedcard-edit/51 Commented Jun 14, 2020 at 4:49
  • It worked when I put URL = "/flash" in the beginning. Commented Jun 15, 2020 at 9:02

1 Answer 1

0

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>
Sign up to request clarification or add additional context in comments.

8 Comments

Unfortunately I don't have access to the card object in my template
in your createDynamicURL how do you set the cardID ?
It comes from a different part of my js file
Anyway, you can get the card in your view and use it in the template. Although, When you set cardID in a javascript, it means that you can have it in your template.
Could you please elaborate on how exactly I should be using cardID in my template?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.