Django1.8若表单条目查询结果和数据库不匹配,则在同一页面上显示警告消息,而不是“None”或引发异常pag

2024-05-23 15:59:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我很感激下面的答案,但很抱歉我仍然没有解决这个问题,也许我没有正确理解它们。因此,为了得到更清楚的答案,我悬赏了一下。在

用户在表单中输入一些信息后,这些信息作为一个查询来过滤数据库得到结果,如果数据库中没有相应的记录,我怎么可能在当前页面或重定向页面上显示一个警告,提醒用户“没有对应的数据”。在

enter image description here

举例说明:如果用户输入“EU”和“India”,数据库中肯定没有对应的记录。表单允许用户将字段留空。在

我以前用的是raisevalidationerror,如果查询结果和数据库不匹配,它将转到一个黄色的“异常”页面,这是不友好的。我想在提交后立即在同一表单页面上显示错误消息:

视图.py

from django.contrib import messages

class InputFormView(FormView):
template_name = 'entryform.html'
form_class = EntryForm

def get_success_url(self):
    params = {
        'department': self.request.POST.get('company'),
        'person': self.request.POST.get('region')
    }
    return ''.join([reverse('final'), '?', urllib.urlencode(params.items())])

class FinalView(ListView):
    context_object_name = 'XXX'
    template_name = 'XXX.html'
    model = Final

    def get_queryset(self):
        form = InputForm(self.request.GET)        
        if form.is_valid():
            department = form.cleaned_data['department']
            person = form.cleaned_data['person']

            if department !="" and person !="":
                if Final.objects.filter(department=department,person=person).exists():
                    queryset=Final.objects.filter(department=department,person=person)
                    return queryset
                else:
                    msg="no corresponding data exists!"
                    form.add_error('department', msg)
                    form.add_error('person', msg)

            elif department =="" and person !="":
                if Final.objects.filter(person=person).exists():
                    queryset=Final.objects.filter(person=person)
                    return queryset
                else:
                    msg="no corresponding data exists!"
                    form.add_error('department', msg)
                    form.add_error('person', msg)

            elif ........


        else:     #if form not valid
            messages.error(request, "Error")

    def get_context_data(self,**kwargs):
        query_set = self.get_queryset()
        if query_set is not None:
            context["sales"] = self.get_queryset().aggregate(Sum('sales'))

html

^{pr2}$

如果我不使用ValidationError方法,它将重定向到结果页,将所有内容显示为“None”。但我想显示一条警告信息。我在网上看到了一个ajax示例,有点复杂。有没有更容易实现的方法

提前谢谢。在

谢谢。在


Tags: 用户selfform数据库datagetifrequest
3条回答

如果我理解正确,FinalView应该只过滤GET参数?在

如果是这样的话,你真的需要表格吗?你好像想说“没有对应的数据存在!”如果没有结果? 通用Listview自动填充self.object_列表(或上下文对象名称)来自get_queryset,因此是一个简单的check对象_列表。存在消息模板()中的消息应足以呈现错误代码。。。在

为了做一个简单的过滤器,我将提供一个我通常在您的示例中使用的技术示例:

class FinalView(ListView):

    def get_queryset(self):
        qs = super(FinalView, self).get_queryset()
        filter_fields = ('department', 'person')  # the fields to filter on
        query_dict = {}  # filter query
        for param in self.request.GET:  # iterate all params
            if param in filter_fields:  # is param a filter we want to use?
                value = self.request.GET.get(param)
                if value:  # Have value? otherwise ignore
                    query_dict[param] = value
        return qs.filter(**query_dict)  # Execute filter

    def get_context_data(self, **kwargs):
        kwargs = super(FinalView, self).get_context_data(**kwargs)
        if self.object_list.exists():  # Did we get objects? (this can also be done directly in template)
           kwargs['error_msg'] = 'no corresponing data exist!'
       else:
           kwargs["sales"] = self.object_list.aggregate(Sum('sales'))
       # Re-populate form if we want that
       kwargs['form'] = InputForm(initial=self.request.GET)
       return kwargs

不知道它是否符合你的要求。但这是另一种解决办法。在

django形式的精化: django中的表单用于验证输入数据并从字段中创建适当的python类型。(即IntegerField将是整数等)。Roles for forms

在本例中,数据用于过滤查询集。数据本身是有效的,但不是使用数据的结果。在

ListView和窗体的“角色”很重要: 视图过滤查询集,django表单验证输入数据。在

如果我们在执行过滤器后对结果不满意,视图应该处理,如果输入数据不好,django表单应该处理。(即格式错误,空字段或部门不能为空,如果人员已填充等)。在

根据这个问题,我们知道FinalView的输入将是字符串或空的。(在self.request.GET总是字符串或空),这里需要django表单可能会使事情复杂化?在

所有这些逻辑都属于形式本身。如果您将它放在clean方法中,那么验证错误将被现有的Django逻辑捕获,并且您可以使用{{ form.non_field_errors }}在模板中显示该错误。在

如果您一直使用django<;1.7,那么可以使用self._errors.add(感谢@Sayse)。如果您使用的是django 1.7或更新版本,则可以使用^{}

This method allows adding errors to specific fields from within the Form.clean() method, or from outside the form altogether; for instance from a view.

The field argument is the name of the field to which the errors should be added. If its value is None the error will be treated as a non-field error as returned by Form.non_field_errors().

The error argument can be a simple string, or preferably an instance of ValidationError. See Raising ValidationError for best practices when defining form errors.

您应该在formclean方法中或在视图中调用form.is_valid()之前,检查数据库中是否没有相应的记录,并将错误附加到字段:

form.addError("region", ValidationError('No corresponding data exists'))

PS:要打开“黄色异常页”,请关闭设置中的DEBUG

相关问题 更多 >