我有一个包含django_table2表的django模板,并且还接受一个文件:
{% extends 'portal/base.html' %}
{% load render_table from django_tables2 %}
{% block title %}{{user.first_name }} {{ user.last_name }} Portal{% endblock %}
{% block content %}
<input type=button value="Back" onClick="javascript:history.go(-1);">
<h4>Currently registered vehicles:</h4>
<div class='vehlist'>
<form action="/loadlocndb/" method="POST">
{% csrf_token %}
{% render_table veh_list %}
<h4> Location database .csv file</h4>
<input type="file" name="myfile"><br/>
<input type="submit" value="Submit" />
</form>
</div>
{% endblock %}
目前在POST
中传回的唯一内容是所选表格复选框。我如何也传回文件。
views.py
@login_required
def locndb(request):
# This is the basic user landing Page
veh_list =VehicleTable(Vehicle.objects.filter(company__user=request.user))
form = LocnDBForm()
RequestConfig(request).configure(veh_list)
return render(request, 'portal/locndb.html', {"veh_list": veh_list, "form": form})
@login_required
def loadlocndb(request):
if request.method == "POST":
pks = request.POST.getlist("update")
print pks
selected_objects = Vehicle.objects.filter(pk__in=pks)
vlist = []
for i in selected_objects:
vlist.append(i)
return render(request, 'portal/loadlocndb.html',{"vlist":vlist})
forms.py
from django import forms
from django.contrib.auth.models import User
from portal.models import UserProfile, Vehicle
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('milkco', 'compName')
class LocnDBForm(forms.ModelForm):
class Meta:
model = Vehicle
fields = ('vehid','locndb',)
车型
class Vehicle(models.Model):
vehid = models.CharField(max_length = 10)
company = models.ForeignKey(UserProfile, default = 1)
#depot = models.ForeignKey(Depot, default = 1)
locndb = models.FileField(upload_to="optiload/", default= "setting.MEDIA_ROOT/locndb/LocnDB.csv")
class Meta:
db_table = "vehicle"
def __unicode__(self):
return self.vehid
更好的是如何在不选择表格中的至少一个条目以及文件的情况下阻止用户处理。
由于
答案 0 :(得分:1)
我更新了您的loadlocndb
视图:
@login_required
def loadlocndb(request):
if request.method == "POST":
pks = request.POST.getlist("update")
myfile = request.FILES['form_field_name'].file
print pks, myfile
selected_objects = Vehicle.objects.filter(pk__in=pks)
vlist = []
for i in selected_objects:
vlist.append(i)
return render(request, 'portal/loadlocndb.html',{"vlist":vlist})
我还没有测试过,但是这个:request.FILES['form_field_name'].file
将从您的表单中获取该文件。只需将文件表单字段名称替换为'form_field_name'
。
你能把你的代码放在form.py吗?
在您的模板中,您应该将<form action="/loadlocndb/" method="POST">
替换为<form action="/loadlocndb/" method="POST" enctype="multipart/form-data">
。
来自documentation:请注意,如果请求方法是POST,则request.FILES将仅包含数据,并且发布请求的<form>
具有属性enctype =“multipart / form-data”。否则,request.FILES将为空。