我正试图开发一个按钮,通过按钮将其中包含一些单词的CSV上传到DBtable,问题是当我单击该按钮时,什么都没有发生,我不知道是我遗漏了什么,还是我必须用其他方式来做。谢谢
views.py:
def uploadWords(request):
up = request.POST.get('Upload')
if up == "Upload":
if request.user.is_authenticated:
form = UploadFileForm()
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
usr = User.objects.get(username=request.user)
if file.name.endswith(".csv"):
reader = csv.reader(file)
for row in reader:
wt = WordsTable()
wt.user = usr
wt.word1 = row[0]
wt.word2 = row[1]
wt.word3 = row[2]
wt.word4 = row[3]
wt.word5 = row[4]
wt.save()
messages.success(request, "File uploaded successfully")
return redirect("home")
else:
messages.info(request, "File is not csv")
return redirect("home")
context = {'form': form}
return render(request, "base.html", context)
else:
return redirect("index")
urls.py:
urlpatterns = [
path('', views.index, name='index'),
path('home/', views.home, name='home'),
path('login/', views.loginView, name='login'),
path('logout/', views.logoutUser, name='logout'),
path('register/', views.register, name='register'),
path('upload/', views.uploadWords, name='upload'),
]
base.html:
<div style="text-align:center;display:block;">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="upload" accept=".csv, .xlsx">
<br>
<button class="button btn btn-primary" type="submit" name="up" value="Upload">Upload</button>
</form>
</div>
按钮的名称为"向上";,所以你需要更改
up = request.POST.get('up')