CSV上传到数据库似乎不起作用

时间:2019-04-29 20:15:04

标签: python django

我正在设置一个Web应用程序,允许用户上传保存到MEDIA_ROOT的CSV文件,并使用CSV数据更新数据库。但是,我似乎无法正常工作。该文件可以保存,但是数据库不会更新。

我遇到了request.FILES的麻烦,但设法做到了这一点。但我似乎无法使用CSV数据更新数据库。

models.py

import datetime
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import User

class UserData(models.Model):
    user_user = models.ForeignKey(User, on_delete=models.CASCADE )
    user_updated = models.DateTimeField(auto_now=True)
    user_contract_number = models.CharField(verbose_name="Contract Number",max_length=30, null=True, blank=True)
    user_ticket_number = models.CharField(verbose_name="Ticket number",max_length=30, null=True, blank=True)
    user_weigh_bridge_number = models.CharField(verbose_name="Weigh Birdge number",max_length=30, null=True, blank=True)

    def __str__(self):
        return f'{self.user.username} Data'

views.py

from django.http import HttpResponse
from django.template import loader
from django.contrib import messages
from django.contrib.auth import login, authenticate
from django.contrib.auth.decorators import login_required
from data_user.models import UserData
import csv, io
from datetime import datetime

@login_required
def user_data(request):
    if request.method == 'POST':
        ud_form = UserDataForm(request.POST, request.FILES, instance=request.user.userprofile)
        if ud_form.is_valid():
            ud_form.save()
            csv_file = request.FILES['user_user_data']
            data_set = csv_file.read().decode('UTF-8')
            io_string = io.StringIO(data_set)
            for column in csv.reader(io_string, delimiter=','):
                _, created = UserData.objects.update_or_create(
                    user_user=username,
                    user_contract_number=column[0],
                    user_ticket_number=column[1],
                    user_weigh_bridge_number=column[2],
                    )
            messages.success(request, f'Congratulations {request.user.first_name} ! You have uploaded your waste data')
            return redirect('users:profile-overview')
    else:
        ud_form = UserDataForm(instance=request.user.userprofile)

    return render(request, 'users/user_data.html', {'ud_form':ud_form})

user_data.html

{% extends 'pages/about_you_profile.html' %}
{% load crispy_forms_tags %}
{% block profile %}

<div class="c-layout-page">
    {% include "users/partials/_profile_header.html" %}
    <div class="container">

        {% include 'users/partials/_profile_sidebar.html' %}

        <div class="c-layout-sidebar-content ">
            <div class="c-content-title-1">
                <h3 class="c-font-uppercase c-font-bold">Upload data</h3>
                {% include 'users/partials/_profile_user_type_text.html' %}
                <div class="c-line-left">
                </div>
                <div class="content-section">

                    <form id="new_user_form" method="POST" enctype="multipart/form-data">
                        {% csrf_token %}
                        <fieldset class="form-group">
                            {{ ud_form|crispy }}
                        </fieldset>
                        <div class="form-group">
                            <button type="submit" class="btn btn-lg c-theme-btn c-btn-square c-btn-uppercase c-btn-bold">Upload</button>
                        </div>
                    </form>

                </div>
                <div class="c-content-box c-size-md ">

            </div>
        </div>
    </div>
</div>
{% endblock profile %}

test_data.csv

contract_number,ticket_number,weigh_bridge_number
218,WTN1234,MC1234
231,WTN1235,MC1235

我希望在admin上注册的应用程序包含csv数据,但什么都不会出现。

0 个答案:

没有答案