django上传csv文件,将内容添加到数据库中

问题描述 投票:0回答:1

我创建了一个表单来上传 csv 文件,并希望将数据放入我的模型中 这是我的 models.py。这是一份简单的调查问卷,包含有关一个人的基本信息。还有第二种模型记录文件的上传时间:

class Upload(CreatedUpdatedModel):
    uploaded_at = models.DateTimeField(auto_now_add=True, unique=True)


class Submission(CreatedUpdatedModel):
    upload = models.ForeignKey(Upload, on_delete=models.CASCADE)
    managed_people_answers = models.ManyToManyField('ManagedPeople')
    political_affiliation_answers = models.ManyToManyField('PoliticalAffiliation')
    religion_answers = models.ManyToManyField('Religion')
    veteran_status_answers = models.ManyToManyField('VeteranStatus')
    submission_time = models.DateTimeField()
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    state = models.CharField(max_length=50, blank=True)
    email = models.EmailField(max_length=50, blank=True)
    street_address = models.CharField(max_length=50, blank=True)
    city = models.CharField(max_length=50, blank=True)
    zip_code = models.CharField(max_length=50, blank=True)
    telephone_number = models.CharField(max_length=50, blank=True)
    birthday = models.DateField(blank=True, null=True)
    income = models.CharField(max_length=50, choices=Income.choices)
    occupation_type = models.CharField(max_length=50, choices=OccupationType.choices, blank=True)
    highest_level_of_education = models.CharField(max_length=50, choices=Education.choices, blank=True)
    do_you_own_a_business = models.CharField(max_length=50, blank=True, default=False, choices=OwnBusiness.choices)
    gender = models.CharField(max_length=50, blank=True)

这是我的 forms.py 它只是一个简单的表单,可以根据需要上传多个文件,取自 django 文档:

class MultipleFileInput(forms.ClearableFileInput):
    allow_multiple_selected = True


class MultipleFileField(forms.FileField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault("widget", MultipleFileInput())
        super().__init__(*args, **kwargs)

    def clean(self, data, initial=None):
        single_file_clean = super().clean
        if isinstance(data, (list, tuple)):
            result = [single_file_clean(d, initial) for d in data]
        else:
            result = single_file_clean(data, initial)
        return result


class UploadForm(forms.Form):
    file = MultipleFileField()

这是我的模板,base.jinja 仅包含一些用于 bootstrap 和 dropzone 的 css 和 js 链接以及脚本:

{% extends 'core/base.jinja' %}
{% block title %}
  Upload
{% endblock %}
{% block body %}
  <div>
    <form class="dropzone" action="/upload/" method="post">
      {% csrf_token %}
      {{ form }}
      <input class="btn btn-primary" type="submit" value="Submit">
    </form>
  </div>
{% endblock %}

我使用 pandas 将 csv 数据加载到我的模型中 这是我的观点.py:

class UploadView(FormView):
    template_name = 'upload.jinja'
    form_class = UploadForm
    success_url = reverse_lazy('data')

    def form_valid(self, form):
        Upload.objects.get_or_create(uploaded_at=datetime.datetime.now())
        file = form.cleaned_data['file']
        df = pd.read_csv(file)
        data = df.fillna('')
        for index, row in data.iterrows():
            Submission.objects.get_or_create(
                submission_time=row['Submission Time'],
                first_name=row['First name'],
                last_name=row['Last name'],
                state=row['State'],
                email=row['email'],
                street_address=row['Street Address'],
                city=row['City'],
                zip_code=row['Postal / Zip code'],
                telephone_number=row['Telephone Number'],
                birthday=row['Birthday'],
                income=row['Income'],
                occupation_type=row['Occupation Type'],
                highest_level_of_education=row['Highest Level of Education'],
                have_managed_people_before=row['Have you ever managed other people?'],
                do_you_own_a_business=row['Do You own a business'],
                political_affiliation=row['Political Affiliation'],
                religion=row['Religion'],
                gender=row['Gender or Sexual Orientation'],
                veteran_status=row['Are you a veteran or member of the military'],
            )
        return super().form_valid(form)

所以我的数据库没有填充任何数据。它确实重定向到“数据”页面,该页面只是带有表格的视图。关于为什么会发生这种情况的任何线索?

python django pandas django-models django-forms
1个回答
0
投票

检查您的 url 路径,可能是从 .../upload 重定向到 .../upload/ 并且您的 POST 请求重定向到带有结尾斜杠的 GET 路径

© www.soinside.com 2019 - 2024. All rights reserved.