Django: страница обновлена, когда я нажимаю на файл импорта, и не появляется сообщение.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Django: страница обновлена, когда я нажимаю на файл импорта, и не появляется сообщение.

Сообщение Anonymous »

Я работаю над веб -приложением Django с питанием, и я хочу настроить представление администратора одной из моих моделей.
Я сделал пользовательский шаблон для страницы добавления и переопределять функцию сохранения в классе администратора для обработки входного файла перед сохранением.

Код: Выделить всё

@admin.register(RMABGD)
class RMABGDAdmin(BaseModelAdmin):
list_display = ('name', 'code_RMA', 'type_BGD', 'Partenaire', 'date_creation', 'RMA_BGD_state')
list_filter = ('type_BGD', 'RMA_BGD_state', 'city')
search_fields = ('name', 'code_RMA', 'Partenaire')

add_form_template = "admin/spatial_data/RMABGD/change_form.html"
change_form_template = "admin/spatial_data/RMABGD/change_form.html"

def process_excel_import(self, request):
excel_file = request.FILES.get('excel_file')
if not excel_file:
messages.error(request, "No file was selected. Please choose an Excel file.")
return False
try:
df = pd.read_excel(excel_file)

required_headers = ["code RMA", "code ACAPS", "Dénomination RMA", "Ville", "Adresse", "Longitude", "Latitude", "Type BGD", "Partenaire", "Date création", "Etat BGD RMA"]
missing_headers = [header for header in required_headers if header not in df.columns]

if missing_headers:
messages.error(request, f"Missing required fields: {', '.join(missing_headers)}")
return False
else:
# If all headers are correct, process data
rows_imported = 0
errors = 0
for index, row in df.iterrows():
try:
# Process row data
obj = RMABGD(
code_ACAPS=row["code ACAPS"],
code_RMA=row["code RMA"],
name=row["Dénomination RMA"],
address=row["Adresse"],
city=row["Ville"],
location=f'POINT({row["Longitude"]} {row["Latitude"]})',
type_BGD=row["Type BGD"],
Partenaire=row["Partenaire"],
date_creation=row["Date création"],
RMA_BGD_state=row["Etat BGD RMA"]
)
obj.save()
rows_imported += 1
except Exception as e:
messages.error(request, f"Error in row {index + 1}: {str(e)}")
errors += 1

if rows_imported > 0:
messages.success(request, f"Successfully imported {rows_imported} rows")
return True
if errors > 0:
messages.warning(request, f"Failed to import {errors} rows. See details above.")
if rows_imported == 0:
messages.error(request, "No rows were imported.  Please check your file and try again.")
return rows_imported > 0
except Exception as e:
messages.error(request, f"Error processing file: {str(e)}")
return False

def save_model(self, request, obj, form, change):
self.process_excel_import(request)
super().save_model(request, obj, form, change)
< /code>
И это соответствующий шаблон для добавления: < /p>
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}

{% block content %}

{% if messages %}
[list]
{% for message in messages %}
[*]{{ message }}
{% endfor %}
[/list]
{% endif %}


{% csrf_token %}




Excel File:

Upload an Excel file with the required columns




[b]{% trans 'Required fields in the imported file:' %}[/b]
[list]
[*]code RMA
[*]code ACAPS
[*]Dénomination RMA
[*]Ville
[*]Adresse
[*]Longitude
[*]Latitude
[*]Type BGD
[*]Partenaire
[*]Date création
[*]Etat BGD RMA
[/list]






{% endblock %}
Когда я нажимаю файл Import, страница обновляется и не отображается сообщение, как если бы функция файла процесса не выполнена

Подробнее здесь: https://stackoverflow.com/questions/795 ... ge-appears
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»