我正在尝试使用 django 的 inline_formset 上传多个文件附件。所以,基本上我是使用 jquery 动态生成表单集并允许用户上传多个文件。我的实现在 Firefox 和 Chromium 上运行良好;但是在 IE9 上这不起作用。我没有收到任何错误消息或类似的东西;但是,我没有看到上传的文件保存在服务器上。任何建议将不胜感激!
谢谢,
这是我遇到的问题的代码:
views.py:(仅相关部分)
@login_required
def save_patent_idea_page(request):
if request.method =='POST':
form = PatentIdeaSaveForm(request.POST)
if form.is_valid():
idea = PatentIdea.objects.create(
industry = form.cleaned_data['industry'],
abstract = form.cleaned_data['abstract'],
description = form.cleaned_data['description'],
title= form.cleaned_data['title'],
#############################################
#share_ind = form.cleaned_data['share_ind'] #
#############################################
user = request.user
)
idea.save()
patentfileformset =
PatentFileFormset(request.POST, request.FILES, instance=idea)
if patentfileformset.is_valid():
patentfileformset.save();
return HttpResponseRedirect(
'/user/ideas/'
)
else:
form = PatentIdeaSaveForm(initial={
'description':'Please Type your desc here ....',
'title':'Specify a title here ....',
'abstract':'Type your abstract here ....'
})
patentfileformset = PatentFileFormset(instance=PatentIdea())
variables = RequestContext(request, {
'form' : form,
'patentfileset' : patentfileformset
})
return render_to_response('patentidea_save.html', variables)
########################## END views.py
models.py(仅相关部分):
class PatentIdea(models.Model):
industry = models.ForeignKey(PatentIndustry)
abstract = models.CharField(max_length=500, blank=True, null=True)
description = models.CharField(max_length=2100, blank=True, null=True)
title= models.CharField(max_length=50, blank=True, null=False)
######################################################################
#share_ind = models.IntegerField(max_length=2, blank=True, null=True)#
######################################################################
user = models.ForeignKey(User)
###############################################################################
#PatentFile = models.FileField(upload_to='patentideas', blank=True, null=True)#
###############################################################################
Last_update = models.DateTimeField(auto_now=True)
def __unicode__(self):
return '%s, %s' % (self.user.username, self.abstract)
class PatentFile(models.Model):
patentidea = models.ForeignKey(PatentIdea)
PatentFile = models.FileField(upload_to='patentideas', blank=True,
null=True)
patentfilename = models.CharField(max_length=60)
######################### END models.py
forms.py(仅相关部分):
PatentFileFormset = inlineformset_factory(PatentIdea, PatentFile,
formset = BaseInlineFormSet,
formfield_callback=custom_field_callback,
extra=4, max_num=0, can_delete=True)
def custom_field_callback(field):
if field.name == 'FieldOfStudy':
return field.formfield(label='Field Of Study');
if field.name == 'grad_month':
return field.formfield(label='Graduation');
if field.name == 'grad_year':
return field.formfield(label='');
if field.name == 'delete':
return field.formfield(label='Delete');
if field.name == 'posDesc':
return forms.CharField(label='Position Desc', max_length=600,
widget=forms.Textarea(attrs={'cols':'100','rows':'4'}));
if field.name == 'emp_fr_month':
return field.formfield(label='From');
if field.name == 'emp_to_month':
return field.formfield(label='To');
if field.name == 'emp_fr_year':
return field.formfield(label='');
if field.name == 'emp_to_year':
return field.formfield(label='');
if field.name == 'PatentFile':
return forms.FileField(label='',
widget=forms.FileInput(attrs={'class':'patentfile_cls'}));
if field.name == 'patentfilename':
return forms.CharField(label='',
widget=forms.TextInput(attrs={'readonly': True, 'size':10,
'class':'patentfile_cls2'}));
else:
return field.formfield();
######################### END forms.py
Patentidea_save.js(仅相关部分):
$('#id_patent_file_add').click(function(ev){
ev.preventDefault();
//alert('Hi 1');
var count = $('#id_display_patentfile_list ul')
.children('li[id^="display_patentfile-"]').length
var tmplMarkup = $('#patentfile-template').html();
var compiledTmpl = _.template(tmplMarkup, { id : count});
$('div[id="id_tmp_form"]').empty();
$('div[id="id_tmp_form"]').append(compiledTmpl);
popup = $('#id_patentfile_set-'+count+'-PatentFile').trigger('click');
// $(popup.document).ready(function() {
// alert(popup.selector);
// console.log('ready');
// $(popup).on('unload', function () {
// console.log('unloaded');
// });
// });
});
$('#id_tmp_form').on('change','input[id^="id_patentfile_set-"][id$="-PatentFile"]',
function() {
var count = $('#id_display_patentfile_list ul')
.children('li[id^="display_patentfile-"]').length
uploaded_filename = $('#id_patentfile_set-'+count+'-PatentFile').val();
$('#id_patentfile_set-'+count+'-patentfilename').val(uploaded_filename);
//alert(uploaded_filename+this.files[0].size);
var filesize = this.files[0].size;
//alert(filesize);
dots = uploaded_filename.split(".")
//get the part AFTER the LAST period.
fileType = dots[dots.length-1];
var tmp_content = $('div[id="patentfile-'+count+'"]').clone();
$('#id_patent_file').append(tmp_content);
$('div[id="id_tmp_form"]').empty();
$('#id_patentfile_set-'+count+'-PatentFile').attr('val',uploaded_filename);
$('#id_display_patentfile_list ul').append('<li id=display_patentfile-'+count+
' class="attachment_cls"></li>');
var attachment_envelope = $('<div id="id_ae-'+count+'" class="drawing"></div>').css({
overflow: 'hidden',
border: '2px solid #228B22',
width: '125px',
height: '80px'
});
attachment_envelope.appendTo($('#display_patentfile-'+count));
$('<span>'+fileType+' </span>').appendTo(attachment_envelope);
$('<span>'+filesize+'KB</span>').appendTo(attachment_envelope);
$('<a href="#" class="delete_button_cls3"'+
'title="click to delete" id="id_delete_patent_file-'+count+
'"><img width="12" height="12" alt="delete sign"'+
'src="/staticfiles/images/delete.png"></a>').appendTo(attachment_envelope);
$('<hr />').appendTo(attachment_envelope);
$('<span class="filename_cls">'+uploaded_filename+'</span>').
appendTo(attachment_envelope);
var count = $('#id_display_patentfile_list ul').
children('li[id^="display_patentfile-"]').length
$('#id_patentfile_set-TOTAL_FORMS').attr('value', count);
});
################# END专利idea_save.js
专利idea_save.html
{% extends "base.html" %}
{% block external %}
<script src="{{ STATIC_PREFIX }}js/patentidea_save.js" type="text/javascript"
charset="utf-8"></script>
{% endblock %}
{% block title %}Save Patent Idea{% endblock %}
{# {% block head %}Save Patent Idea{% endblock %} #}
{% block content %}
<form method ="post" action="." enctype="multipart/form-data">{% csrf_token %}
<div id="id_block_title">
{{ form.title.errors }}
<label for="id_title" class="required">Title</label>
{{ form.title}}
</div>
<div id="id_block_industry">
{{ form.industry.errors }}
<label for="id_industry" class="required" >Industry</label>
{{ form.industry}}
</div>
<div id="id_block_abstract">
{{ form.abstract.errors }}
<label for="id_abstract" class="required" >Abstract</label>
{{ form.abstract}}
<br><span id="remainingCount1">000</span> characters left
</div>
<div id="id_block_description">
{{ form.description.errors }}
<br><br>
<label for="id_description" class="required">Description</label>
{{ form.description}}
<br><span id="remainingCount2">000</span> characters left<br><br>
</div>
<div id="id_block_uploadfile">
<span id="id_PatentFile" title='Please Load Related File(s), if any'>
Load Related File(s)</span>
<a id="id_patent_file_add" href="#" class="patent_file_add_cls">[Add]</a>
<div id="id_tmp_form"></div>
{{ patentfileset.management_form }}
<div id="id_patent_file">
{% for pform in patentfileset %}
<div id="id_patent_file-{{ forloop.counter0 }}">
{{ pform.as_p }}
</div>
{% endfor %}
</div>
<div id="id_display_patentfile_list">
<ul>
</ul>
</div>
</div>
<div id="id_block_submit">
<input type="submit" id="id_submit_patentidea" value="Save">
<input type="button" id="id_cancel_patentidea"
onClick="parent.location='{% url cpit.views.main_page %}'"
value="Cancel">
</div>
</form>
<script type="text/html" id="patentfile-template">
<div id="patentfile-<%= id %>" style="display:none">
<p>
<label for="id_patentfile_set-<%= id %>-PatentFile">PatentFile:</label>
<input id="id_patentfile_set-<%= id %>-PatentFile" type="file"
name="patentfile_set-<%= id %>-PatentFile" />
</p>
<p>
<label for="id_patentfile_set-<%= id %>-patentfilename">Patentfilename:</label>
<input id="id_patentfile_set-<%= id %>-patentfilename" maxlength="60"
name="patentfile_set-<%= id %>-patentfilename" type="text" />
</p>
<input id="id_patentfile_set-<%= id%>-patentidea" type="hidden"
name="patentfile_set-<%= id%>-patentidea" />
<input id="id_patentfile_set-<%= id%>-id" type="hidden"
name="patentfile_set-<%= enter code hereid%>-id" />
</div>
</script>
{% endblock %}
######################### END专利idea_save.html