我有一个ChallengeDetailView,它显示了类似博客文章的挑战的详细信息。我在同一页面上也有一个表单字段,它应该得到挑战的答案,并将其与数据库进行比较。到目前为止,这是我所做的;
class ChallengeDetailView(DetailView):
model = Challenge
def get_context_data(self, **kwargs):
context = super(ChallengeDetailView, self).get_context_data(**kwargs)
context['form'] = FlagForm
return context
from django import forms
class FlagForm(forms.Form):
flag = forms.CharField(label='Challenge Flag',required=True)
class FlagFormView(FormView):
form_class = FlagForm
success_url = reverse_lazy('challenge-detail')
我尝试实现如下所示的简单逻辑;
def get_flag(self, request):
if self.request.method == 'POST':
form = FlagForm(request.POST)
if form.is_valid():
flag = form.cleaned_data.get('flag')
if flag == Challenge.flag:
return messages.success("You found the flag!")
else:
return FlagForm()
我试图将其包含在form_valid()方法中,但无法使其在ChallengeDetailView中起作用。我愿意接受任何建议。我来自Symfony的背景并且对Django很陌生。
答案 0 :(得分:0)
最后我能够弄清楚。 我在Forms.py
中创建了一个常规表单from django import forms
class FlagForm(forms.Form):
flag = forms.CharField()
在views.py中,我有一个详细信息视图和一个带有SingleObjectMixin的表单视图,可用于当前帖子。
class ChallengeDisplay(DetailView):
model = Challenge
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = FlagForm()
return context
具有SingleObjectMixin的表单视图;
class ChallengeFormEntry(SingleObjectMixin, FormView):
template_name = 'ctf/challenge_detail.html'
form_class = FlagForm
model = Challenge
def post(self, request, *args, **kwargs):
if request.method == 'POST':
form = FlagForm(request.POST)
if form.is_valid():
flag = form.cleaned_data.get('flag')
if self.get_object().flag == flag:
messages.success(request, 'good job!')
else: messages.warning(request, 'Try again!')
form = FlagForm()
return super().post(request, *args, **kwargs)
def get_success_url(self):
return reverse('challenge-detail', kwargs={'pk': self.get_object().pk, 'slug':self.get_object().slug})