简体   繁体   English

Django pre_save 信号和 ModelAdmin 自定义错误消息

[英]Django pre_save signal and ModelAdmin custom error message

I have a model whose pre_save() signal is connected to a remove service (json, REST, etc.) in the following way:我有一个模型,其 pre_save() 信号通过以下方式连接到删除服务(json、REST 等):

  1. before saving locally, query the remote service, asking for remote insertion本地保存前,查询远程服务,请求远程插入
  2. remote service does its things, the main being checking that a relevant entry does not already exist.远程服务做它的事情,主要是检查相关条目是否已经存在。
  3. On success (HTTP 201), all is good, the local model uses the remote service response to populate the db.成功时(HTTP 201),一切都很好,本地模型使用远程服务响应来填充数据库。
  4. on failure, the service returns an HTTP 400 (the status code is debatable but that is for a different question on SO :-) )失败时,服务返回 HTTP 400(状态码是有争议的,但这是针对 SO 上的另一个问题 :-))
  5. The error response is in the following form:错误响应格式如下:

    {'local_model_field': [u'This element already exists']}

  6. The local model pre_save signal then raises a ValidationError :本地模型 pre_save 信号然后引发ValidationError

    raise ValidationError(json_response['local_model_field'][0])

This works nicely.这很好用。

Now, on the django admin, when I try to simulate the remote insertion of an already-existing object, I get a 500 page, which is fine but not ideal.现在,在 django 管理员上,当我尝试模拟远程插入一个已经存在的对象时,我得到一个 500 页,这很好但并不理想。

Is there any way to have the pre_save() error bubble all the way up to the ModelAdmin and be displayed as a standard error message, populated with the relevant content?有没有办法让 pre_save() 错误气泡一直到ModelAdmin并显示为标准错误消息,并填充相关内容?

I have tried the following but to no avail:我尝试了以下但无济于事:

def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
    """
    trying to display the right message when pre_save() fails on model save() method (after asking CC)
    """
    try:
        return super(ObjectAdmin, self).changeform_view(request, object_id, form_url, extra_context)
    except IntegrityError as e:
        self.message_user(request, e, level=messages.ERROR)
        return HttpResponseRedirect(form_url)

Is a ValidationError the right thing to do? ValidationError是正确的做法吗? Knowing that the pre_save() must lock out any chance of ending with with duplicates both locally and remotely.知道pre_save()必须锁定任何以本地和远程重复结尾的机会。 The main reason is that the local/remote object creation can be made form the admin but also from other website instances/types (front-end, end-user facing, for example).主要原因是本地/远程对象创建可以由管理员进行,也可以从其他网站实例/类型(例如,前端、面向最终用户)进行。

Thanks谢谢

Not sure if this is still relevant.不确定这是否仍然相关。 But the way I solved this is by creating a ModelForm:但我解决这个问题的方法是创建一个 ModelForm:

class AuthorAdminForm(forms.ModelForm):

    def clean(self):
        # or some api calls here
        if self.instance.id > 4:
            self.instance.name = "4+"
        else:
            ValidationError("Id is bigger that 4")
        return super().clean()

And then by adding the form to the admin model:然后通过将表单添加到管理模型:

class AuthorAdmin(admin.ModelAdmin):
    form = AuthorAdminForm

This clean() method will ensure that you could add/modify fields before you hit the model save() method and still throw a ValidationError if something goes south like a 404 error when hitting a url这个clean()方法将确保您可以在点击模型save()方法之前添加/修改字段,并且如果在点击 url 时出现404错误等问题,仍然会抛出ValidationError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM