Я пытаюсь создать форму, используя Django FormView, который перенаправит меня на страницу, если форма верна. Я хочу видеть сообщение об успехе в модальном окне после перенаправления. Это не сработало, так как я получал KeyError: 'pk' при отправке формы.
views.py:
class ApplyView(FormView):
template_name = 'vouchers/apply.html'
model = Voucher
voucher = None
form_class = VoucherApplyForm
def form_valid(self, form):
self.code = form.cleaned_data['code']
now = timezone.now()
Voucher.objects.filter(code__iexact=self.code,
valid_from__lte=now,
valid_to__gte=now,
usage_limit=3,
active=True)
form.apply_voucher()
return super(ApplyView, self).form_valid(form)
def get_success_url(self):
messages.add_message(self.request, messages.INFO,
"Congratulations! You've successfully redeemed {{ voucher.value }} "
"{{ voucher.get_type_display }} off the selected item(s).")
return reverse('vouchers:apply', args=(self.kwargs['pk'],))
class VoucherDetailView(generic.DetailView):
template_name = 'vouchers/detail.html'
model = Voucher
def get_context_data(self, **kwargs):
context = super(VoucherDetailView, self).get_context_data(**kwargs)
context['redemption_form'] = VoucherApplyForm(initial={'voucher':self.object})
return context
urls.py:
urlpatterns = [
path('<int:pk>/', views.VoucherDetailView.as_view(), name='detail'),
path('<int:voucher_id>/apply/', views.ApplyView.as_view(), name='apply'),
]
detail.html:
<h1>Redeem your voucher!</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'vouchers:apply' voucher.id %}" method="post">
{{ redemption_form }}
{% csrf_token %}
<input type="submit" value="Apply">
</form>
apply.html:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
И я закончил тем, что получил ошибку следующим образом:
return reverse('vouchers:detail', args=(self.kwargs['pk'],))
KeyError: 'pk'
Ваша помощь очень ценится. Спасибо!