あなたがちょうどあなたは間違いなくクラスベースDetailViewになっているはずですProposal
詳細に行きたい場合。
AJAX
リクエストで作成するか、フォームで作成することができます。タイプの両方のために、あなたはそれをキャッチするView
を持っている必要があります。
HTMLフォーム
:あなたが持っている必要があり、あなたのテンプレートで
:
<form id="formId" method="post" action="{% url 'catch-proposal' %}">
{% csrf_token %}
<input type="hidden" name="proposal_id" value="{{ proposal.id }}"/>
<p><button type="submit" class="btn btn-primary btn-lg">Learn more</a></p>
<!-- <input type="submit" class="btn btn-primary btn-lg" value="Learn more"/> -->
</form>
をそれはurls.py
からあなたView
に行きます:
url(r'^post/for/proposal/$', catch_proposal, name='catch-proposal'),
# if your view class-based
# url(r'^post/for/proposal/$', CatchProposal.as_view(), name='catch-proposal')
は、その後、あなたのビューであなたがキャッチしますPOSTデータ:
def catch_proposal(request):
if request.method == "POST":
print(request.POST) # have a look for your post params
return reverse_lazy('index') # your response, you can make it on your own
AJAX:
それをチェック! AJAX and Django
ページには、任意のHTMLフォームページがAJAX経由でPOSTリクエストを行う
せずにAJAXを使用し、ページが必要なCSRFのクッキーがあることを引き起こすcsrf_tokenとHTMLのフォームを持っていません送信されます。
解決策:ページを送信するビューでensure_csrf_cookie()を使用してください。スクリプトで
定義:あなたのLearn More
ボタンの
function sendPost(proposalId) {
$.ajax({
url: '{% url 'catch-proposal' %}', // or just /ajax/catch/proposal/
method : "POST",
data: {
// your data to send key => val
'id': proposalId
},
dataType: 'json', // it can be xml, json, script, html
success: function (result) {
// Do something if your request was successful (code=200)
// All response data stored in result
console.log(result)
},
error : function(xhr,errmsg,err) {
// Error case
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
を:
<p><button class="btn btn-primary btn-lg" role="button" onclick="sendPost({{ proposal.id }})">Learn more</button></p>
そして、あなたはあなたのView
でそれをキャッチします:
@ensure_csrf_cookie # Since you sending POST request without form tag
def catch_proposal(request):
response_data = {} # your response
if request.method == 'POST':
# your post request
if 'id' not in request.POST: # check the param from POST
# Provide error message
response_data['error_message'] = "Can't find ID in POST params..."
else:
# Do whatever
proposal_id = int(request.POST.get('id'))
try:
proposal = Proposal.objects.get(id=transport_id)
response_data['success'] = True
except Proposal.DoesNotExist:
response_data['success'] = False
return JsonResponse(response_data)
else:
response_data = {
'error_message': 'Something is going very strange and wrong...'
}
return JsonResponse(response_data)
作成を追加するView
〜urls.py
:
from .views import catch_proposal # or yourapp.views
....
url(r'^ajax/catch/proposal/$', catch_proposal, name='catch_proposal'),
....