Django:如何使表单具有条件



我有一个包含两个字段的表单。应该要求用户只选择其中一个。不是两者都有,也不是一个都没有。我试图通过覆盖Django Doc:中描述的clean方法来解决这个问题

forms.py

class ConfigureWorkout(forms.Form):
first_exercise = forms.ModelChoiceField(empty_label="select", label="Choose First Exercise", queryset=FirstExercise.objects.all(), required=False) 
sec_exercise = forms.ModelChoiceField(empty_label="select", label="Choose Sec Exercise", queryset=SecExercise.objects.all(), required=False)
def clean(self):
first_exercise = self.cleaned_data.get("first_exercise")
sec_exercise = self.cleaned_data.get("sec_exercise")
if first_exercise and sec_exercise:
raise forms.ValidationError("Enter either a First Exercise or a Secondary Exercise.")
else:
return self.cleaned_data

views.py

def configure(request):
configure_workout = ConfigureWorkout()
if request.method == "GET":
return render(request, "userprofile/some.html", configure_workout)
else:
return render(request, "app/other.html")

模板

<form action="{% url 'configure' %}" method="POST">
{% csrf_token %}
{{ configure_workout }}
<input type="submit" name="configuration_completed">
</form>

但是,如果我通过选择表单中的两个字段来测试这一点,就不会显示/引发错误。我成功地通过了表格,并被发送到";other.html";。

我错过了什么?提前感谢您的帮助:(

您似乎没有向表单传递实际数据。也许这会有所帮助:

def configure(request):
configure_workout = ConfigureWorkout()
if request.method == "GET":
return render(request, "userprofile/some.html", configure_workout)
else:
configure_workout = ConfigureWorkout(request.POST)
configure_workout.is_valid()
configure_workout.clean()
return render(request, "app/other.html")

基于@trafalinos答案并查看表单上的文档,我建议执行以下操作:

forms.py:中

class ConfigureWorkout(forms.Form):
first_exercise = forms.ModelChoiceField(empty_label="select", label="Choose First Exercise", queryset=FirstExercise.objects.all(), required=False) 
sec_exercise = forms.ModelChoiceField(empty_label="select", label="Choose Sec Exercise", queryset=SecExercise.objects.all(), required=False)
def clean(self):
cleaned_data = super().clean()  # compare documentation
first_exercise = cleaned_data.get("first_exercise")
sec_exercise = cleaned_data.get("sec_exercise")
if first_exercise and sec_exercise:
raise forms.ValidationError("Enter either a First Exercise or a Secondary Exercise.")
else:
return self.cleaned_data

和(归功于trafalino(在views.py:

def configure(request):
if request.method == "GET":
configure_workout = ConfigureWorkout()
return render(request, "userprofile/some.html", configure_workout)
else:
configure_workout = ConfigureWorkout(request.POST)
configure_workout.clean()
return render(request, "app/other.html")

相关内容

  • 没有找到相关文章

最新更新