Django

GreenBeanΒ·2022λ…„ 2μ›” 11일
0
post-thumbnail

Django

Admin Page Custom

  • csv 파일 μ—…λ‘œλ“œ

change_list.html

  • app/templates/admin/custom_change_list.html 생성
  • django의 admin/change_list.html 상속
  • λΆ€λͺ¨μ˜ { extrahead block } μˆ˜μ •
    • λΆ€λͺ¨μ˜ extrahead 뢀뢄을 κ·ΈλŒ€λ‘œ λ°›κΈ° μœ„ν•΄ {{ block.super }}
# custom_change_list.html
{% extends 'admin/change_list.html' %}

{% block object-tools %}
    <a href="import-csv/">Import CSV</a>
    <br />
    {{ block.super }}
{% endblock %}


# csv_form.html
{% extends 'admin/base.html' %}

{% block content %}
    <div>
        <form action="." method="POST" enctype="multipart/form-data">
            {{ form.as_p }}
            {% csrf_token %}

                <button type="submit">Upload CSV</button>
        </form>
    </div>
    <br />

{% endblock %}

admin.py

  • μž¬μ •μ˜ν•œ ν…œν”Œλ¦Ώ μ—°κ²°
class CsvImportForm(forms.Form):
    csv_file = forms.FileField()

class SendTextAdmin(admin.ModelAdmin):
    change_list_template = "admin/custom_change_list.html"
    
    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('import-csv/', self.import_csv),
        ]
        return my_urls + urls
    
    def import_csv(self, request):
        if request.method == "POST":
            csv_file = request.FILES["csv_file"]
            reader = csv.reader(csv_file)
            # 읽은 데이터 μ‚¬μš©
            # ...
            self.message_user(request, "Your csv file has been imported")
            return redirect("..")
        
        form = CsvImportForm()
        payload = {"form": form}
        return render(
            request, "admin/csv_form.html", payload

κ²°κ³Ό

profile
🌱 Backend-Dev | hwaya2828@gmail.com

0개의 λŒ“κΈ€