[英]How to call specific fields from models.py in the views.py in Django
我想在成功提交表单后添加一条消息,其中部分消息涉及来自应用程序 model 的参数值。
我尝试使用如下方法:
视图.py:
class ApplyView(FormView):
template_name = 'vouchers/apply.html'
model = Voucher
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, voucher_id):
voucher = Voucher.objects.filter(pk=voucher_id)
discount_value = voucher.value
discount_type = voucher.get_type_display
messages.add_message(self.request, messages.INFO,
"Congratulations! You've successfully redeemed %s"
" %s off the selected item(s)." % (
discount_value,
discount_type,
))
return reverse('vouchers:apply', kwargs={'voucher_id': self.kwargs['voucher_id']})
网址.py:
urlpatterns = [
path('<int:pk>/', views.VoucherDetailView.as_view(), name='detail'),
path('<int:voucher_id>/apply/', views.ApplyView.as_view(), name='apply'),
]
但是,我收到了一个 TypeError:
return HttpResponseRedirect(self.get_success_url())
TypeError: get_success_url() missing 1 required positional argument: 'voucher_id'
非常感谢您的帮助。 干杯!
get_success_url
在您的视图的父 class 中调用。 根据定义,它除了self
之外没有任何 arguments 。 如果您需要在该方法上定义其他 arguments,那么您需要更新调用者以提供它们。 这意味着您将需要覆盖其他一些方法。
另一个选项,我怀疑您更喜欢使用的选项是从视图实例的 kwargs 中获取voucher_id
。 这可以通过self.kwargs['voucher_id']
来完成
def get_success_url(self):
voucher = Voucher.objects.get(pk=self.kwargs['voucher_id'])
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.