无法从Django中上传的CSV文件中将数据插入模型

时间:2020-03-04 17:53:39

标签: python django csv django-models

单击“提交”后,没有任何反应,我认为是因为它无法从.models导入Mobile,因此从forms.py的 from .models导入Mobile 未被使用。如何导入它,以便我可以成功上传CSV文件并将数据插入到Mobile模型中。

forms.py 看起来像这样

import io
import csv
from django import forms
from .models import Mobile



class DataForm(forms.Form):
    data_file = forms.FileField()

    def clean_data_file(self):
        f = self.cleaned_data['data_file']

        if f:
            ext = f.name.split('.')[-1]
            if ext != 'csv':
                raise forms.ValidationError('File Type not supported')
            return f

    def process_data(self):
        f = io.TextIOWrapper(self.cleaned_data['data_file'].file)
        Mobile = csv.DictReader(f)

        for i in Mobile:
            Mobile.objects.create_data(i['mobile_owner'], i['mobile_number'])

views.py 看起来像这样:

from .models import Mobile
from django.views.generic import TemplateView

from .forms import DataForm
from django.views.generic import FormView


class DataView(FormView):
    template_name = 'sms/mobile.html'
    form_class = DataForm
    success_url = '/upload/'

    def form_valid(self, form):
        form.process.data()
        return super().form_valid(form)

mobile.html 看起来像这样

{% extends 'base/base.html' %}

{% block title %}Add SMS Data{% endblock title %}


{% block scripts %}

{% endblock scripts %}


{% block content %}

<form action="{% url 'mobile' %}" method="POST" enctype="multipart/form-data">
  {% csrf_token %}
  <label>Upload mobile numbers</label>
  <input type="file" name="data_file">
  <input type="submit" value="submit">
</form>


{% endblock content %}

urls.py 看起来像这样:

from django.urls import path, include
from . import views

urlpatterns = [
    path('mobile', views.index, name='mobile'),
    ]

1 个答案:

答案 0 :(得分:0)

嗨,看来您在form_valid方法中有错字。

from .models import Mobile
from django.views.generic import TemplateView

from .forms import DataForm
from django.views.generic import FormView


class DataView(FormView):
    template_name = 'sms/mobile.html'
    form_class = DataForm
    success_url = '/upload/'

    def form_valid(self, form):
        form.process_data()
        return super().form_valid(form)

form.process.data()更改为form.process_data(),您应该会很好。