On my previous version QuestionImage had a FK relation with Question, so using QuestionAdmin would lead to simple UI to upload images straight from the Question edit page.
Something similar to:
Now I need to have an ability to share the same image + meta information through multiple instances of Question, which I did through QuestionImageIntermediate table relation.
The problem for me to have an ability to upload an image from the same Question page. Since with the current code configuration I provided below, I have to create an instance of an QuestionImage instance, and only after I can select it while filling the Inline while editing Question.
My idea was to “somehow” add “upload file” button using forms.ImageField(), manually create an instance of QuestionImage, attach it to Inline instance, and pass all the validations.
That was not the first idea, but all of them failed. The one I described is failing since an image field collects errors before clean() called, I assume it validates far earlier, in to_python() most likely. So with this approach I have to write a lot of code, inventing multiple methods, some of them would pass validations, some of them would catch another ones. Looks fragile, like I really over engineering this feature.
Could you please suggest a better approach? or At least assure that there is no simple way to upload a file through ManyToMany table in Admin panel?
I have the following model:
class QuestionImageIntermediate(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
image = models.ForeignKey("QuestionImage", on_delete=models.CASCADE)
class QuestionImage(models.Model):
image = models.ImageField(upload_to="questions", null=True)
text = models.TextField("Picture description", null=True)
class Question(models.Model):
text = models.TextField("Text of the questions", null=False)
question_images = models.ManyToManyField(
"QuestionImage",
through="QuestionImageIntermediate",
related_name="questions",
)
and the following admin.py:
class QuestionImageInline(admin.TabularInline):
model = QuestionImageIntermediate
extra = 1
#form = QuestionImageForm
class QuestionAdmin(admin.ModelAdmin):
inlines = [
QuestionImageInline,
]
Thank you very much.