从表单集中添加要添加的字段_

2024-06-18 04:23:09 发布

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

我有以下代码管理员py公司名称:

from django.contrib import admin
from .models import Timesheet
from .models import Action
import requests


class ActionAdmin(admin.TabularInline):
    model = Action
    extra = 0


class TimesheetAdmin(admin.ModelAdmin):
    inlines = [ActionAdmin]

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            url = 'https://xxx.xxxxxx.com/api.php'
            contents = requests.get(url)

            if contents.status_code == 200 and contents.json()['result'] == 'success':
                instance.ticket_title = contents.json()['subject']
                instance.save()
            else:
                form.add_error('?????', 'Ticket ID Not Found')
        formset.save_m2m()


admin.site.register(Timesheet, TimesheetAdmin)

我有罚单区表格集。如果我通过“票证号”将发生此错误:

^{pr2}$

没错,因为ticket_id不在时间表表单中,而是在ActionForm中,后者是时间表表单中的一个表单集。在

我应该将什么传递给add_错误以指示此字段?在


Tags: instancefromimport表单adminmodelssavecontents
2条回答

查看add_error文档后,该方法接受两个参数:

Form.add_error(field, error)

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.

对于您的案例,您必须将其用作:

^{pr2}$

更新save_formset函数如下

def save_formset(self, request, form, formset, change):
    instances = formset.save(commit=False)
    for instance in instances:
        url = 'https://xxx.xxxxxx.com/api.php'
        contents = requests.get(url)

        if contents.status_code == 200 and contents.json()['result'] == 'success':
            instance.ticket_title = contents.json()['subject']
            instance.save()
        else:
            raise forms.ValidationError('?????', 'Ticket ID Not Found')
    formset.save_m2m()

它可能会解决你的问题

相关问题 更多 >