ModelForm初始化问题

2024-10-03 11:15:45 发布

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

我试图修改我的Django ModelForm__init__构造函数,以便它接受一个传递的变量('admin'),查看admin == True,如果是这样,则将两个字段('applicator\uconfiration'&;applicator\uinterest_stmt')显示为不可修改的。字段显示为不可修改(如需要),但是.update()函数没有发生,因为它没有通过if form.is_valid检查。我已经检查了form.non_field_errorsform.errors,但什么也没有。如果__init__方法被注释掉,则更新工作正常。在

有没有想过我会错过什么?诚然,我对构建一个构造器还没有很好的理解。我们将非常感谢您的帮助。在

class ApplicationForm(ModelForm):

    class Meta:
        model = Application
        fields = ('program', 'status', 'applicant_affirmation', 'applicant_interest_stmt', 'applicant_school', 'applicant_major', 'applicant_school_2', 'applicant_major_2', 'gpa_univ', 'estimated_grad_semester')
        widgets = {
            'applicant_interest_stmt': Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'estimated_grad_semester': Select(),
        }

    def __init__(self, admin, *args, **kwargs):
        super(ApplicationForm, self).__init__(*args, **kwargs)
        if admin:
            self.fields['applicant_interest_stmt'].widget.attrs['disabled'] = 'disabled'
            self.fields['applicant_affirmation'].widget.attrs['disabled'] = 'disabled'


    def clean(self):
        from django.core.exceptions import ValidationError
        cleaned_data = super(ApplicationForm, self).clean()
        applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
        applicant_affirmation = cleaned_data.get('applicant_affirmation')
        if not applicant_interest_stmt:
            msg = u'Please provide an interest statement.'
            self._errors["applicant_interest_stmt"] = self.error_class([msg])
        if not applicant_affirmation:
            msg = u'Please check the affirmation checkbox.'
            self._errors["applicant_affirmation"] = self.error_class([msg])
        return cleaned_data

应用模型:

^{pr2}$

源代码段视图.py公司名称:

if request.POST:
    app_form = ApplicationForm(request.POST)
    app_form.fields['estimated_grad_semester'].widget.choices = build_semester_list('', 12)

    if app_form.is_valid():
        print 'form is valid...'
        app_instance = get_object_or_404(Application, id=app_id)
        fields = {'program': app_form.cleaned_data['program'],
                  'status': app_form.cleaned_data['status'],
                  'applicant_id': application.applicant_id,
                  'applicant_affirmation': app_form.cleaned_data['applicant_affirmation'],
                  'applicant_interest_stmt': app_form.cleaned_data['applicant_interest_stmt'],
                  'applicant_school': app_form.cleaned_data['applicant_school'],
                  'applicant_major': app_form.cleaned_data['applicant_major'],
                  'applicant_school_2': app_form.cleaned_data['applicant_school_2'],
                  'applicant_major_2': app_form.cleaned_data['applicant_major_2'],
                  'gpa_univ': app_form.cleaned_data['gpa_univ'],
                  'estimated_grad_semester': app_form.cleaned_data['estimated_grad_semester'],
                  '_created_by': app_instance._created_by,
                  '_created': app_instance._created,
                  '_updated_by': user.eid,
                  }
        try:
            application = Application(pk=app_id, **fields)
            application.update()
        except Exception, exception:
            return HttpResponse('Error: ' + str(exception))

        return redirect('application_view', app_id=app_id)

    else:
        print 'app_form is NOT valid'
else:
    # -------------------------------------------
    # render the application using GET
    # -------------------------------------------
    app_form = ApplicationForm(admin=admin_user, instance=application)
    app_form.fields['estimated_grad_semester'].widget.choices = build_semester_list('', 12)

所做的最终修改导致所需的修复:

在视图.py在

if request.POST:
    app_form = ApplicationForm(admin=admin_user, data=request.POST)

在表单.py在

def __init__(self, admin, *args, **kwargs):
    super(ApplicationForm, self).__init__(*args, **kwargs)
    self.admin = admin
    if self.admin:
        self.fields['applicant_interest_stmt'].widget.attrs['readonly'] = True
        self.fields['applicant_affirmation'].widget.attrs['readonly'] = True


def clean(self):
    from django.core.exceptions import ValidationError
    cleaned_data = super(ApplicationForm, self).clean()
    if not self.admin:
        applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
        applicant_affirmation = cleaned_data.get('applicant_affirmation')
        if not applicant_interest_stmt:
            msg = u'Please provide an interest statement.'
            self._errors["applicant_interest_stmt"] = self.error_class([msg])
        if not applicant_affirmation:
            msg = u'Please check the affirmation checkbox.'
            self._errors["applicant_affirmation"] = self.error_class([msg])
    return cleaned_data

注意:在“申请者确认”布尔字段中获取不可修改的设置仍然存在一个挥之不去的问题,但我将与此问题分开解决。在


Tags: selfformappfieldsdataifadminmsg
1条回答
网友
1楼 · 发布于 2024-10-03 11:15:45

你可能想让管理员成为全班的高官

class ApplicationForm(ModelForm):

class Meta:
    model = Application
    fields = ('program', 'status', 'applicant_affirmation', 'applicant_interest_stmt', 'applicant_school', 'applicant_major', 'applicant_school_2', 'applicant_major_2', 'gpa_univ', 'estimated_grad_semester')
    widgets = {
        'applicant_interest_stmt': Textarea(attrs={'class': 'form-control', 'rows': 5}),
        'estimated_grad_semester': Select(),
    }

def __init__(self, admin, *args, **kwargs):
    super(ApplicationForm, self).__init__(*args, **kwargs)
    self.admin = admin
    if self.admin:
        self.fields['applicant_interest_stmt'].widget.attrs['disabled'] = 'disabled'
        self.fields['applicant_affirmation'].widget.attrs['disabled'] = 'disabled'


def clean(self):
    from django.core.exceptions import ValidationError
    cleaned_data = super(ApplicationForm, self).clean()
    if not self.admin:
        applicant_interest_stmt = cleaned_data.get('applicant_interest_stmt')
        applicant_affirmation = cleaned_data.get('applicant_affirmation')
        if not applicant_interest_stmt:
            msg = u'Please provide an interest statement.'
            self._errors["applicant_interest_stmt"] = self.error_class([msg])
        if not applicant_affirmation:
            msg = u'Please check the affirmation checkbox.'
            self._errors["applicant_affirmation"] = self.error_class([msg])
    return cleaned_data

相关问题 更多 >