有關如何在Django上使用一種形式處理多個重複字段的完整答案,請閱讀本答覆歷史記錄。這將是在Django的一個頁面上處理多種形式的良好實踐的答案。
所以有這個配方,我們需要的是以下幾點:
- 一個視圖,也可以是基於類或基於功能的,在這個例子中,我將使用類 - 因爲它很整潔。
- 提供此視圖的URL,關於它的唯一特殊情況是添加到其末尾的可選參數。
- 具有用於調用右視圖函數的正確設置的模板。
- (可選)您可以使用表單來驗證數據,但這不是要求。
所以,首先要做的第一件事就是創建視圖。這將關注問題分解爲更好的可讀性。
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.http import HttpResponseBadRequest
class PlaceBet(View):
template_name = 'place_bets.html'
context = some_base_context_dict
def get(self, request):
# the user is requesting the game list
self.context['games'] = Game.objects.all()
return render(request, self.template_name, self.context)
def post(self, request, game_id=None):
# the user is submitting one of game's predictions
if not game_id:
return HttpResponseBadRequest('hey, send a game id, you fool!')
game = get_object_or_404(Game, pk=game_id)
# here you can use a Form to validate the data, but hey,
# do your homework
bet = Bet.objects.create(user=request.user, game=game,
team1_score=request.POST.get('team1_score'),
team2_score=request.POST.get('team2_score'))
# bet is saved at this point so now we can now take the user
# elsewhere or i dunno, the same page...
self.context['games'] = Game.objects.all()
self.context['new_bet'] = bet
response = render(request, self.template_name, self.context)
# it's good practice to say you created something
response.status_code = 201
return response
現在,網址都需要一些工作過,你傳遞一個參數,所以......
urlpatterns = [
url(r'^place_bet$', PlaceBet.as_view()),
url(r'^place_bet/(?P<game_id>[^/.]+)', PlaceBet.as_view(), name='place-bet') #name parameter, very important for the future...
]
你的模板是差不多吧,但它需要一些工作:
{% for game in games %}
<!-- the action now points to the URL by name, and passes the game_id -->
<form action="{% url 'place-bet' game.pk %}" method="POST">
{% csrf_token %}
<table>
<tr>
<th class="table-col">
<label for="team1_score">{{ game.team1_name}}</label>
</th>
<th class="table-col">
<!-- you need something to submit -->
<input type="number" name="team1_score" value="{{ game.team1_score }}">
</th>
</tr>
<tr>
<td class="table-col">
<label for="team2_score">{{ game.team2_name}}</label>
</td>
<td class="table-col">
<input type="number" name="team2_score" value="{{ game.team2_score }}">
</td>
</tr>
</table>
<input type="submit" value="Submit" id="submit-button"/>
</form>
{% endfor %}
現在,按下提交按鈕後,瀏覽器將使用編碼遊戲ID的動作URL將POST數據發送到視圖的post
方法,因此不會有任何錯誤。
此代碼可以改善很多,但它會讓你去。
這聽起來像你想要1形式與更多的領域,而不是多種形式。 –
@CarsonCrane我也想過,但是當你預測的遊戲數量變大時,你不覺得事情會失去控制嗎? – Blademaster