I am developing a website for schoolchildren on a voluntary basis, there are several nested models, that is: I have a Question associated with it 1to1 Comment, and a ForeignKey CoImage associated with Comment (I need the ability to add many illustrations to Comment). To edit the entire Question on one page, I use inlineformset_factory.
PROBLEM: when uploading files, for some reason, all images are added to QuImage (these are illustrations to the question that are processed in the same form), even those that were uploaded to CoImage.
My forms:
from .models import Question, QuImage, Comment, CoImage, CoFile
from django.forms import ModelForm, inlineformset_factory
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = [
'year', 'stage', 'grade', 'part', 'number',
'text', 'tags', 'topics',
'flag', 'type']
QuImageFormSet = inlineformset_factory(Question, QuImage, extra = 5, fields=['file', 'label'])
CommentFormSet = inlineformset_factory(Question, Comment, extra = 1, fields=['text'])
CoImageFormSet = inlineformset_factory(Comment, CoImage, extra = 3, fields=['file', 'label'])
My views:
def add(request):
if request.method == 'POST':
addform = QuestionForm(request.POST)
question = quicksave(addform)
if question:
quimageform = QuImageFormSet(request.POST, request.FILES, instance=question)
quicksave(quimageform)
commentform = CommentFormSet(request.POST, instance=question)
comment = quicksave(commentform)
if comment:
coimageform = CoImageFormSet(request.POST, request.FILES, instance=comment)
quicksave(coimageform)
return redirect('problems')
addform = QuestionForm()
quimage = QuImageFormSet()
comment = CommentFormSet()
coimage = CoImageFormSet()
cofile = []
context = {'addform': addform,
'quimage': quimage,
'comment': comment,
'coimage': coimage,
'cofile': cofile}
return render(request, 'add.html', context)
I will be very grateful for your help in solving this problem, you will help a cool project! Is there a good simple way to work with many hierarchically related models in django? All the code is available on github. Note: quicksave is my simple script, which do form.is_valid and save it.