我已经做了很长时间的研究而无法弄清楚。我的Django应用程序链接到我的模型“CostDetl”创建的mysql数据库,我有一个网页来显示我的模型表。在表格中,我有一个文件字段“协议”,我希望网页在单元格中为每个表格行显示浏览和上传表单,如果上传任何内容并且文件字段不为空,则表格单元格只显示文件名,带有打开上传文件的链接。我没有问题显示带链接的上传文件,我可以在管理员上传协议,但我无法弄清楚如何从网页上传。请帮忙!以下是我的所有代码,非常感谢!
设定:
MEDIA_ROOT = '/Users/username/myapp/media'
MEDIA_URL = '/media/'
在项目urls.py中,我添加了:
url(r'^media/', views.UploadAgreementView),
在models.py中:
def content_file_name(instance, filename):
return os.path.join(['content', instance.user.username, filename])
class CostDetl(models.Model):
Provider = models.CharField(null=True, blank=True, max_length=200)
Description = models.CharField(null=True, blank=True, max_length=200)
Agreement = models.FileField(null=True, blank=True, upload_to=content_file_name)
def __unicode__(self):
return self.Provider+' | '+self.Description
def __str__(self):
return self.Provider+' | '+self.Description
查看:
def CostData(request):
costrecordset = CostDetl.objects.all()
context = {'CostDetl1': costrecordset}
return render(request, 'polls/CostDetl.html', context)
def UploadAgreementView(request):
if request.method == 'POST':
form = UploadAgreement(request.POST or None, request.FILES or None)
if form.is_valid():
newdoc = CostDetl(request.FILES['file'])
newdoc.save()
return HttpResponseRedirect(reverse('polls:AgreementUpload'))
else:
form = UploadAgreement()
documents = CostDetl.objects.all()
return render(request,
'polls/CostDetl.html',
{'CostDetl1': documents, 'AgreementUpload': form})
在forms.py中:
from django import forms
from .models import CostDetl
class UploadAgreement(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
在模板中:
{% if CostDetl1 %}
{% load humanize %}
<table>
<tr>
<th>Provider</th>
<th>Expense Description</th>
<th>Agreement</th>
</tr>
{% for i in CostDetl1 %}
<tr>
<td nowrap>{{ i.Provider }}</td>
<td nowrap>{{ i.Description }}</td>
<td nowrap>
{% if i.Agreement %}
<a href="/media/{{ i.Agreement }}">
{{ i.Agreement }}
</a>
{% else %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="file" name="myfile"/>
<input type="submit" name="submit" value="Upload"/>
</form>
{% endif %}
</td>
</tr>
{% endfor %}
</table>
{% endif %}
在urls.py中:
url(r'^CostDetl/$', views.CostData, name='CostDetl1'),
url(r'^Agreement/$', views.UploadAgreementView, name='AgreementUpload'),