无法将数据保存在Django中的数据库中

时间:2018-11-18 02:30:28

标签: django django-models django-views

我正在尝试将CS​​V文件上传到Django,下面描述的代码很好,并且没有错误弹出,但是在提交CSV之后,数据未存储在Django数据库中。当我查看管理页面时,没有详细信息。

models.py

from django.db import models

class Shiftrotainfo(models.Model):
  first_name=models.CharField(max_length=50)
  last_name=models.CharField(max_length=50)
  whichShift = models.CharField(max_length=50)

  def __str__(self):
     return f'{self.first_name} {self.last_name}'

views.py

from django.shortcuts import render
from django.http import HttpResponse
import csv,io
from django.contrib import messages
from .models import Shiftrotainfo

def home(request):
    return HttpResponse('<h1>Shift Rota</h1>')

def upload_rota(request):
    template = "shiftrota/rota_upload.html"
    prompt = {
        'order':'order of the CSV name followed by week shift details'
    }
    if request.method == "GET":
        return render(request,template, prompt)

    csv_file = request.FILES['file']
    if not csv_file.name.endswith('.csv'):
       messages.error(request,'This is not a CSV file')

    data_set = csv_file.read().decode('UTF-8')
    io_string = io.StringIO(data_set)
    next(io_string)

    for column in csv.reader(io_string, delimiter=',', quotechar="|"):
        _,created = Shiftrotainfo.objects.update_or_create(
            first_name=column[0],
            last_name=column[1],
            whichShift=column[2]

        )
    context ={}
    return render(request, template, context)

此处rota_upload.html

{% if messages %}
    {% for message in messages %}
        <div {% if message.tags %} class="{{ message.tags }}" {% endif %}>
            <strong>{{ message|safe }}</strong>
        </div>
    {% endfor %}
{% else %}
    {{order}}
        <form method="post" enctype="multipart/form-data">{% csrf_token %}
            <label>Upload File</label>
            <input type="file" name="file">
            <p>Only Accepts CSV Files</p>
            <button type="save">Upload</button>
        </form>
{% endif %}

亲切建议,我有没有想补充什么? 这是我的完整代码:https://github.com/srinivasgadi77/schedule

你能在这里帮忙吗

0 个答案:

没有答案