Django upload csv to DB via template with function

I made a function with "runscript" on Django. I wanna know how can I upload a CSV file via a template with my function.

this is my function:

def run():
    df = pd.read_csv("scripts/Combination.csv", dtype=str)

    df = df[pd.isnull(df["id"])]

    def sub_budget_owner_found(v_BO, v_SBO):
        try:
            Employee.objects.get_or_create(name=v_BO)
            v_BO_obj = Employee.objects.get(name=v_BO)
        except:
            v_BO_obj = Employee.objects.get(name="99999 No Budget Owner")

        try:
            Employee.objects.get_or_create(name=v_SBO)
            v_SBO_obj = Employee.objects.get(name=v_SBO)
        except:
            v_SBO_obj = Employee.objects.get(name="99998 No Sub Budget Owner")

        return SubBudgetOwner.objects.get_or_create(
            budget_owner=v_BO_obj, sub_budget_owner=v_SBO_obj
        )

    for i, row in df.iterrows():
        v_subsidiary = row["Subsidiary"]
        v_department = row["Department"]
        v_account = row["Account"]
        v_sub_budget = row["Sub Budget"]
        v_budget_owner = row["Budget Owner"]
        v_sub_budget_owner = row["Sub Budget Owner"]

        Combination.objects.get_or_create(
            subsidiary=Subsidiary.objects.get_or_create(name=str(v_subsidiary))[0],
            department=Department.objects.get_or_create(name=str(v_department))[0],
            account=Account.objects.get_or_create(name=str(v_account))[0],
            sub_budget=SubBudget.objects.get_or_create(name=str(v_sub_budget))[0],
            budget_owner=sub_budget_owner_found(v_budget_owner, v_sub_budget_owner)[0],
        )
        print(i, row)

I use Django view classes. The purpose is to upload new data via CSV file in the GUI.

Thanks a lot

So I found a solution for this.

my urls.py

path("combinationimport/", views.import_combination, name="combination_import"),

in my views.py

def import_combination(request):
    if "GET" == request.method:
        return render(request, "budget/combination_import.html", {})
    else:
        excel_file = request.FILES["excel_file"]
        wookbook = openpyxl.load_workbook(excel_file)
        worksheet = wookbook.active
        print(worksheet)
        data = worksheet.values

        # Get the first line in file as a header line
        columns = next(data)[0:]
        df = pd.DataFrame(data, columns=columns)

        def sub_budget_owner_found(v_BO, v_SBO):
            try:
                Employee.objects.get_or_create(name=v_BO)
                v_BO_obj = Employee.objects.get(name=v_BO)
            except:
                v_BO_obj = Employee.objects.get(name="99999 No Budget Owner")
            try:
                Employee.objects.get_or_create(name=v_SBO)
                v_SBO_obj = Employee.objects.get(name=v_SBO)
            except:
                v_SBO_obj = Employee.objects.get(name="99998 No Sub Budget Owner")

            return SubBudgetOwner.objects.get_or_create(
                budget_owner=v_BO_obj, sub_budget_owner=v_SBO_obj
            )

        new_data_entry = []
        excel_data = list()

        # iterating over the rows and
        # getting value from each cell in row
        for row in worksheet.iter_rows():
            row_data = list()
            for cell in row:
                row_data.append(str(cell.value))
            excel_data.append(row_data)

        for i, row in df.iterrows():
            v_subsidiary = row["Subsidiary"]
            v_department = row["Department"]
            v_account = row["Account"]
            v_sub_budget = row["Sub Budget"]
            v_budget_owner = row["Budget Owner"]
            v_sub_budget_owner = row["Sub Budget Owner"]
            combo = Combination.objects.get_or_create(
                subsidiary=Subsidiary.objects.get_or_create(name=str(v_subsidiary))[0],
                department=Department.objects.get_or_create(name=str(v_department))[0],
                account=Account.objects.get_or_create(name=str(v_account))[0],
                sub_budget=SubBudget.objects.get_or_create(name=str(v_sub_budget))[0],
                budget_owner=sub_budget_owner_found(v_budget_owner, v_sub_budget_owner)[
                    0
                ],
            )
            if combo[1] == True:
                new_data_entry.append(f"Row #{i+2}: {combo[0]}")

        return render(
            request,
            "budget/combination_import.html",
            {"excel_data": excel_data, "new_data_entry": new_data_entry},
        )

combination_import.html

XLSX FILE
<form action="{% url "budget:combination_import" %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file"
            title="Upload excel file"
            name="excel_file"
            style="border: 1px solid black; padding: 5px;"
            required="required">
    <p>
        <br>
    <input type="submit" value="Upload" style="padding:5px 15px; 
    background:#3CBC8D; 
    border:0 none;
    cursor:pointer;
    -webkit-border-radius: 5px;
    border-radius: 5px;">
</form>


<hr>

<p>New Records:</p>

{% for q in new_data_entry %}
    <p style="background-color:green; color:white">{{ q }}</p>
{% endfor %} 

<hr>


<p>All Records:</p>

{% for row in excel_data %}
    {% for cell in row %}
        {{ cell }}&nbsp;&nbsp;
    {% endfor %}
    <br>
{% endfor %}

I hope it will help.

Back to Top