2013-07-27 87 views
0

我只是想打電話從模板視圖功能可按,我已經看到了,我有相反的功能做到這一點。我想傳遞一個參數給視圖函數,但我不想在url中顯示它。可能嗎?這裏是我的代碼和錯誤:Django的反向找不到

urls.py

url(r'^perfil/deleteDownloadedTrack/$','principal.views.delete_downloaded_track', name='delete_downloaded_track'), 

views.py

def delete_downloaded_track(request, track):  
    ... 
    return HttpResponseRedirect(reverse('profile_detail')) 

template.html

{% for track in downloadedTracks %} 
    <tr> 
     <td> 
      {{track.name}} 
     </td> 
     <td> 
      <div class="botoForm" onclick="location.href='{% url "principal.views.delete_downloaded_track" track %}'"> Eliminar </div> 
     </td> 
{% endfor %} 

和錯誤:

Reverse for 'principal.views.delete_downloaded_track' with arguments '(<DownloadedTrack: DownloadedTrack object>,)' and keyword arguments '{}' not found. 

謝謝!

+1

您URLPATTERN需要包括一個部件以捕獲(大概)的DownloadedTrack實例的ID,那麼你的{%URL%}標籤需要軌道 - > track.id。請參閱:https://docs.djangoproject.com/en/dev/topics/http/urls/ – AdamKG

回答

2

推薦由HTML標準來處理任何改變服務器上的數據的請求的方式是使用POST請求。

{% for track in downloadedTracks %} 
    <tr> 
     <td> 
      {{track.name}} 
     </td> 
     <td> 
      <form method="POST" action="{% url principal.views.delete_downloaded_track %}" id="delete-form-{{ track.id }}"> 
       {% csrf_token %} 
       <input type="hidden" name="track_id" value="{{ track.id }}" /> 
       <div class="botoForm" onclick="document.getElementById('delete-form-{{ track.id }}').submit()"> Eliminar </div> 
      </form> 
     </td> 
{% endfor %} 

{% csrf_token %}通過驗證你的人發送這種形式也是其發送回通過POST請求的人防止跨站點僞造請求。只需使用以下方式檢索您的視圖中的ID:

if request.method == 'POST': 
    id = request.POST.get("track_id", None) 
    track = Track.objects.get(id=id) 

通過POST發送的數據不會顯示在url中。

+0

是@knbk你的方式是更好的和更清潔的方式。 – quekshuy

1

如果你不希望顯示的參數在你的URL,那麼你可能想在將它作爲查詢參數,例如

<host_and_path>/perfil/deleteDownloadedTrack/?track_id=<some_track_id>

所以,你的看法是這樣的:

def delete_downloaded_track(request): 
    track_id = request.GET.get('track_id') 
    # get track based on track_id and delete it. 

和模板像這樣(假設你在delete_downloaded_track的反向傳遞作爲模板背景delete_url):

{% for track in downloadedTracks %} 

    <!-- template code --> 

    {% with delete_url|add:"?track_id="|add:track.id as url_with_id %} 
     <a href="{{url_with_id|safe}}">Delete</a> 
    {% endwith %} 

{% endfor %}