|
| 1 | +from typing import Union |
| 2 | + |
1 | 3 | from django.contrib.admin import helpers |
2 | 4 | from django.contrib.admin.utils import lookup_field, quote |
3 | 5 | from django.core.exceptions import ObjectDoesNotExist |
4 | 6 | from django.db import models |
5 | 7 | from django.db.models import ( |
| 8 | + FileField, |
6 | 9 | ForeignObjectRel, |
7 | 10 | ImageField, |
8 | 11 | JSONField, |
@@ -36,6 +39,30 @@ def label_tag(self) -> SafeText: |
36 | 39 |
|
37 | 40 | return format_html("<label{}>{}</label>", flatatt(attrs), capfirst(label)) |
38 | 41 |
|
| 42 | + @property |
| 43 | + def url(self) -> Union[str, bool]: |
| 44 | + field, obj, model_admin = ( |
| 45 | + self.field["field"], |
| 46 | + self.form.instance, |
| 47 | + self.model_admin, |
| 48 | + ) |
| 49 | + |
| 50 | + try: |
| 51 | + f, attr, value = lookup_field(field, obj, model_admin) |
| 52 | + except (AttributeError, ValueError, ObjectDoesNotExist): |
| 53 | + return False |
| 54 | + |
| 55 | + if not self.is_file(): |
| 56 | + return False |
| 57 | + |
| 58 | + if hasattr(obj, field): |
| 59 | + field_value = getattr(obj, field) |
| 60 | + |
| 61 | + if field_value and hasattr(field_value, "url"): |
| 62 | + return field_value.url |
| 63 | + |
| 64 | + return False |
| 65 | + |
39 | 66 | def is_json(self) -> bool: |
40 | 67 | field, obj, model_admin = ( |
41 | 68 | self.field["field"], |
@@ -73,6 +100,20 @@ def is_image(self) -> bool: |
73 | 100 |
|
74 | 101 | return isinstance(f, ImageField) |
75 | 102 |
|
| 103 | + def is_file(self) -> bool: |
| 104 | + field, obj, model_admin = ( |
| 105 | + self.field["field"], |
| 106 | + self.form.instance, |
| 107 | + self.model_admin, |
| 108 | + ) |
| 109 | + |
| 110 | + try: |
| 111 | + f, attr, value = lookup_field(field, obj, model_admin) |
| 112 | + except (AttributeError, ValueError, ObjectDoesNotExist): |
| 113 | + return False |
| 114 | + |
| 115 | + return isinstance(f, (ImageField, FileField)) |
| 116 | + |
76 | 117 | def contents(self) -> str: |
77 | 118 | contents = self._get_contents() |
78 | 119 | contents = self._preprocess_field(contents) |
|
0 commit comments