Django MultiValueDictKeyError при попытке получить "type"
У меня есть страница django, которая экспортирует содержимое списка в csv. Имя файла настроено на включение имени организации, но я хочу, чтобы оно также включало тип файла. Насколько я могу судить, значения берутся отсюда:
<div class="p-1 col-12 fw-bold mb-2">
<label class="text-r mb-1">Select File Type:</label>
<select name="type" class="form-select" aria-label="Default select example">
<option value="accounts">Accounts</option>
<option value="contacts">Contacts</option>
<option value="membership">Membership</option>
<option value="cg">Community Group</option>
<option value="cgm">Community Group Member</option>
<option value="so">Sales Order</option>
<option value="item">Item</option>
<option value="event">Event</option>
<option value="tt">Ticket Type</option>
<option value="si">Schedule Item</option>
<option value="attendee">Attendee</option>
</select>
</div>
<div class="p-1 col-12 fw-bold mb-2">
<label class="text-r mb-1">Organization Name:</label>
<input class="form-control" placeholder="Organization Name" type="text" name="name" required />
</div>
Функция python, которая вызывает его, выглядит следующим образом:
class CsvView(View):
def post(self, request, *args, **kwargs):
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
data = request.POST["raees"]
name = request.POST["name"]
d_type = request.POST["type"]
data = list(data.split(","))
last = data[-1]
first = data[0]
data[0] = first.replace("[", "")
data[-1] = last.replace("]", "")
row = 0
col = 0
for i in data:
i = i.replace("'", "")
worksheet.write(row, col, i)
row = row + 1
workbook.close()
output.seek(0)
filename = f"{name} {d_type} Issue Tracker.xlsx"
response = HttpResponse(
output,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
response["Content-Disposition"] = "attachment; filename=%s" % filename
return response
Часть name = request.POST["name"], кажется, работает нормально, но не часть d_type = request.POST["type"], которую я добавил. Я также попробовал d_type = request.POST.get("type"), но безрезультатно. В первом случае я получаю ошибку, указанную в заголовке, но последний код (как и d_type = request.GET.get("type") просто не извлекает значение, когда это необходимо. Есть предыдущая функция, которая вызывает "type" без проблем, так что я не уверен, что здесь нужно. Любая помощь будет оценена по достоинству.
(Если вам интересно, что это за "предыдущая функция", которая вызывает "тип", то она следующая):
class HomeView(View):
def get(self, request, *args, **kwargs):
return render(request, "myapp/file-form.html")
def post(self, request, *args, **kwargs):
type = request.POST["type"]
file = request.FILES['file'].name
# file = request.FILES["file"].read().decode("utf-8")
name = request.POST["name"]
# dataset = Dataset().load(file, format="csv")
dataset = pd.read_csv(request.FILES['file'], encoding = "ISO-8859-1")
if type == "accounts":
errors = accounts_checker(dataset)
elif type == "contacts":
errors = contacts_checker(dataset)
elif type == "membership":
errors = member_ship_checker(dataset)
elif type == "cg":
errors = cg_checker(dataset)
elif type == "cgm":
errors = cgm_checker(dataset)
elif type == "so":
errors = so_checker(dataset)
elif type == "item":
errors = item_checker(dataset)
elif type == "event":
errors = event_checker(dataset)
elif type == "tt":
errors = tt_checker(dataset)
elif type == "si":
errors = si_checker(dataset)
elif type == "attendee":
errors = att_checker(dataset)
context = {
"results": errors,
"name": name,
}
return render(request, "myapp/results.html", context=context)
Вы можете попробовать следующий вариант, если не можете найти ошибку:
#your Forms.py
from django import forms
my_d_types=(("accounts","Accounts"),("contacts","Contacts"),
("membership","Membership"),("cg","Community Group"),
("cgm","Community Group Member"),("so","Sales Order"),
("item","Item"),("event","Event"),("tt","Ticket Type"),
("si","Schedule Item"),("attendee","Attendee")
)
class CsvViewForm(forms.Form):
#include this to replace existing 'd_type' variable in your form related to the CsvView
d_type=forms.ChoiceField(label='Select File Type:',choices=my_d_types,required=False)
#yourfile.HTML
#replace the section <select .... </select> with the following
<div>
<p>{{ form.d_type.label_tag }}</p>
<p>{{ form.d_type }}</p>
</div>
#your Views.py
from .forms import CsvViewForm
class CsvView(View):
form = CsvViewForm(request.POST)
Вы также можете проверить, что HTML-код включает "enctype="multipart/form-data"" в начале тега формы, в зависимости от того, что есть в остальной части файла, поскольку вы показали только ту часть, которая, по вашему мнению, может содержать ошибку.