I have a model for file uploads defined like this:
class UploadedFile(models.Model):
fpath = models.FileField(...)
sig = models.CharField(max_length=32) # for md5 of data, computed with post_save
and I have another model, named MTest, that has this:
class MTest(models.Model):
file1 = models.ForeignKey("UploadedFile",related_name="first_file")
file2 = models.ForeignKey("UploadedFile",related_name="second_file")
... # other fields here
I want to show a form for MTest
, and I want to allow the user to perform the upload of the files in 1 step. From what I read here and here , I have this:
def x_attachment_t(request):
c = {}
MTestFormset = inlineformset_factory(UploadedFile, MTest, fk_name="file1",extra=1)
c.update({"formset":MTestFormset})
return render_to_response("form.html",c,context_instance=RequestContext(request))
The problem is, I still get the data prepopulated for the file upload fields, and I only have a select box for the second file. Here's the code from the template:
{% for form in formset.forms %}
<div class="span-21 last">
{% for field in form %}
<font color="red">{{ field.errors }}</font>
<div class="span-4">{{ field.label_tag }}</div>
<div class="span-17">{{ field }}</div>
{% endfor %}
</div>
{% endfor %}
For now, I'm blocked, and I don't know how to continue. I would appreciate any help :)
Your approach here isn't quite right. The inline formset is a pattern to "edit multiple MTest
s linked to the same UploadedFile
".
I would create a model forms for UploadedFile
and Mtest
. Exclude the file1
and file2
fields from the MtestModelForm
. Put two uploaded file forms and the MtestModelForm
in the same html <form>
tag using the prefix
argument.
Then in your view, if all three forms are valid, use save the MtestModelForm
with commit=False
, and update file1
and file2
before saving to the db.
Here's a skeleton of the view
def my_view(request):
if request.method == "POST"
file1_form = UploadedFileForm(request.POST, request.FILES, prefix="file1")
file2_form = UploadedFileForm(request.POST, request.FILES, prefix="file2")
mtest_form = MTestForm(data=request.POST, prefix="mtest")
if mtest_form.is_valid() and file1_form.is_valid and file2_form.is_valid():
file1 = file1_form.save()
file2 = file2_form.save()
mtest = mtest_form.save(commit=False)
mtest.file1 = file1
mtest.file2 = file2
mtest.save()
return HttpResponseRedirect("/success-url/")
# case for invalid form data or GET request omitted
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.