使用OneToOneField和customd参数进行复杂的Django ModelForm验证

时间:2016-03-15 22:22:02

标签: django validation modelform

很抱歉这个冗长的问题。我对django模型验证有一个复杂的情况。我有一个模型UserProject准备好并创建了许多对象。我还有另一个模型Action_Inputs来接受多个参数,这是与UserProject的onetoonefield关系。我确实需要Action_Inputs的一个字段的自定义输入参数。但我不能保持形式。

models.py

class UserProject(models.Model):
    pid = models.CharField(max_length=10, null=False, unique=True)
    email = models.EmailField(max_length=254, null=False)
    directory = models.CharField(max_length=255)

class Action_Inputs(models.Model):
    userproject = models.OneToOneField(UserProject, null=False)
    method = models.CharField(max_length=255)
    file = models.FileField(upload_to='userdata')

现在我有以下ModelForm,它接受一个自定义输入参数jobid,从url捕获,这是一个字符串,以回到之前的UserProject pid:

class ActionInputsForm(ModelForm):

    def __init__(self, jobid, *args, **kwargs):
        super(ActionInputsForm, self).__init__(*args, **kwargs)
        self.fields['userproject'].initial = jobid

    class Meta:
        model = Action_Inputs
        fields = ['userproject', 'method', 'file'] # userproject will be hidden

    def clean_userproject(self):
        userproject = self.cleaned_data['userproject']
        if len(userproject) != 10:
            raise forms.ValidationError("---PID error.")
        return UserProject.objects.get(pid=userproject)

    def clean(self):

        return self.cleaned_data

在我的views.py

def parameters_Inputs(request, jobid):

    if request.method == "POST":
        form1 = ActionInputsForm(request.POST, request.FILES, jobid)

        if form1.is_bound:
            form1.save()
            return render(request, 'goodlog.html', {'jobid': jobid})

    elif request.method == "GET":
        form1 = ActionInputsForm(jobid)

    return render(request, 'inputsform.html',
        {'form1': form1, 'jobid': jobid})

现在request.POST ['userproject']为空,这意味着jobid尚未被 init 修改,request.FILES看起来正确但验证为false。它说Unicode对象没有attrite get,这与上传的文件有关。什么是错的?非常感谢。

以下作品:(感谢Vladimir Danilov)

def __init__(self, jobid, *args, **kwargs):
    super(ActionInputsForm, self).__init__(*args, **kwargs)
    self.fields['userproject'].initial = UserProject.objects.get(pid=jobid)


def clean_userproject(self):
    userproject = self.cleaned_data['userproject']
    if not userproject:
        raise forms.ValidationError("---UserProject not found.")
    return userproject

def parameters_Inputs(request,jobid):

if request.method == "POST":
    form1 = ActionInputsForm(jobid, request.POST, request.FILES)

.......

1 个答案:

答案 0 :(得分:0)

没有回答,但你的意思是arr1而不是ActionInputsForm这些行吗?

Action_Inputs

另外,你应该写form1 = Action_Inputs(request.POST, request.FILES, jobid) # ... form1 = Action_inputs(jobid) 。 因为在您的情况下,ActionInputsForm(jobid, request.POST, request.FILES)将是jobid