开发者

How to use validation to make a clickable, pseudo-readonly FileField in the admin?

I'm trying to have a FileField that is clickable in the admin but is also readonly. There's currently an open ticket for this issue, but I need a workaround now. I'm trying to write a validator for my admin class but I'm running into an exception when I run it. This is what I currently have:

class ModelWithAttachment(models.Model):
    attachment = FileField(upload_to=somewhere, blank=True)

class ModelWithAttachmentAdminForm(forms.ModelForm):
    class Meta:
        model = ModelWithAttachment

    def clean_attachment(self):
    开发者_Go百科    attachment = self.cleaned_data['attachment']
        return self.cleaned_data['attachment']

class ModelWithAttachmentAdmin(admin.ModelAdmin):
    form = ModelWithAttachmentAdminForm

Currently I get an AssertionError with no exception supplied at the line attachment = self.cleaned_data['attachment']. If I replace that line with cleaned_data = self.cleaned_data, I get the same AssertionError. As far as I understand it, self.cleaned_data is supposed to have been created earlier in the validation process, so I don't understand why it doesn't seem to exist.

Secondly, my goal with this whole scheme is to check the value of the attachment being submitted through the admin against the value it currently holds, and reject it (raise a ValidationError) if the two differ - essentially making the attachment 'readonly' while allowing it to be clicked in the admin. Is this a feasible goal? Is there another better/simpler way to accomplish this?


I figured it out. My approach was correct, with clean_attachment being defined as:

def clean_attachment(self): 
    if 'attachment' in self.changed_data: 
        raise forms.ValidationError('no!') 

    return self.cleaned_data['attachment'] 

The problem was an old .pyc file getting reused incorrectly. Once I deleted that, it was fine. Hope that helps someone else out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜