gpt4 book ai didi

python - 为什么我的 ValidationErrors 不再呈现?

转载 作者:行者123 更新时间:2023-12-02 02:41:54 29 4
gpt4 key购买 nike

我有一个表单,必须在提交之前检查一些事情,以确保数据有效。在我进行一些更改(从基于类的 View 到基于函数的 View )之前,一切正常,但是当我回去测试所有内容时,我注意到一个非常重要的部分没有正常工作,即数字验证。

以前发生的情况是,如果输入了数据库中没有的数字,用户将在顶部显示错误。如果他们输入了数据库中的数字,但它不是正确的“团队”,那么它会显示错误。我在 forms.py 中处理这个,完全忘记了,因为它以前工作过,我开始使用的所有东西都在 views.py 中。现在,虽然它实际上不会提交表单(因此它仍在执行逻辑),但它不会显示任何错误。它只会重新渲染页面但为空,除非输入的数据正确,否则不会提交任何内容。处理此问题的逻辑是 clean_employee_number。

我不确定我是否在没有注意到的情况下从我的 html 中删除了一些东西,但我一直试图找出可能导致它停止工作的原因,但我无法弄清楚。我也不确定这是否可能是由于小部件造成的,因为我后来进行了更改(它是一个小部件,因为employee_number 与存储在另一个名为 Salesman 的模型中的员工的“id”相关联)。

模型.py

class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area")
station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True)

forms.py
class WarehouseForm(AppsModelForm):
class Meta:
model = EmployeeWorkAreaLog
widgets = {
'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
}
fields = ('employee_number', 'work_area', 'station_number', 'edited_timestamp')

def clean_employee_number(self):
employee_number = self.cleaned_data.get('employee_number')

if employee_number is None:
raise forms.ValidationError("Must enter emp #")
elif employee_number.team is None:
raise forms.ValidationError("Not valid")
elif employee_number.team not in ('WF', 'WP', 'OM') or employee_number.employee_status not in 'A':
raise forms.ValidationError("Employee not valid, please contact manager")

views.py
def enter_exit_area(request):
form = WarehouseForm(request.POST or None)
enter_without_exit = None
exit_without_enter = None

if request.method == 'POST':
temp = request.POST.copy()
form = WarehouseForm(temp)
if form.is_valid():
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
edited_time = form.cleaned_data['edited_timestamp']

if 'enter_area' in request.POST:
new_entry = form.save()
EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now())

# If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N'
enters_without_exits = EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).exclude(pk=new_entry.pk).order_by("-time_in")
if len(enters_without_exits) > 0:
enter_without_exit = enters_without_exits[0]
enters_without_exits.update(time_exceptions='N')

message = 'You have entered %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)

elif 'leave_area' in request.POST:
# Something similar to above

form = WarehouseForm()
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
'exit_without_enter': exit_without_enter,
})

enter_exit_area.html
{% extends "base.html" %}


{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}

{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}

<div>
<div>
<div>{{ form.employee_number.errors.as_text }}</div>
<label>Employee #</label>
{{ form.employee_number }}
</div>

<div>
<div>{{ form.work_area.errors.as_text }}</div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div>{{ form.station_number.errors.as_text }}</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>

<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>

最佳答案

您构建一个新表单,以防它是一个 POST 请求并且该表单无效。您的 enter_exit_area 的工作流程应该是:

def enter_exit_area(request):
enter_without_exit = None
exit_without_enter = None
if request.method == 'POST':
form = WarehouseForm(request.POST)
if form.is_valid():
# …
return redirect('some-view')
else:
form = WarehouseForm()
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
'exit_without_enter': exit_without_enter,
})

请注意, form = WarehouseForm() 是在 elseif request.method == 'POST' 块中构造的。

如果 POST 请求成功,您通常会进行重定向以实现 Post/Redirect/Get pattern [wiki]

关于python - 为什么我的 ValidationErrors 不再呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58961957/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com