上传文件后出现multivaluedictkeyerror

时间:2018-07-29 00:06:25

标签: django file django-views

尝试上传文件时出错 以下是我的文件 和文件后的错误消息 sdfsfsdfsfd 科幻 自卫队 自卫队 s df 自卫队 标清 fs dfsdfsdfsdf 自卫队 标清 fs dfsd F 科幻 科幻 标清 F 科幻 科幻 Model.py

import uuid

from django.conf import settings from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _

from asgiref.sync import async_to_sync

from channels.layers import get_channel_layer

from bootcamp.notifications.models import Notification, notification_handler


class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)


class News(models.Model):
    """News model to contain small information snippets in the same manner as
    Twitter does."""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, related_name="publisher",
        on_delete=models.SET_NULL)
    parent = models.ForeignKey("self", blank=True,
        null=True, on_delete=models.CASCADE, related_name="thread")
    #myfile = models.FileField(null = True,blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    uuid_id = models.UUIDField(
        primary_key=True, default=uuid.uuid4, editable=False)
    content = models.TextField(max_length=280)
    liked = models.ManyToManyField(settings.AUTH_USER_MODEL,
        blank=True, related_name="liked_news")
    reply = models.BooleanField(verbose_name=_("Is a reply?"), default=False)


    class Meta:
        verbose_name = _("News")
        verbose_name_plural = _("News")
        ordering = ("-timestamp",)

    def __str__(self):
        return str(self.content)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        if not self.reply:
            channel_layer = get_channel_layer()
            payload = {
                    "type": "receive",
                    "key": "additional_news",
                    "actor_name": self.user.username

                }
            async_to_sync(channel_layer.group_send)('notifications', payload)

    def get_absolute_url(self):
        return reverse("news:detail", kwargs={"uuid_id": self.uuid})

    def switch_like(self, user):
        if user in self.liked.all():
            self.liked.remove(user)

        else:
            self.liked.add(user)
            notification_handler(user, self.user,
                                 Notification.LIKED, action_object=self,
                                 id_value=str(self.uuid_id),
                                 key='social_update')

    def get_parent(self):
        if self.parent:
            return self.parent

        else:
            return self

    def reply_this(self, user, text):
        """Handler function to create a News instance as a reply to any
        published news.

        :requires:

        :param user: The logged in user who is doing the reply.
        :param content: String with the reply.
        """
        parent = self.get_parent()
        reply_news = News.objects.create(
            user=user,
            content=text,
            reply=True,
            parent=parent
        )
        notification_handler(
            user, parent.user, Notification.REPLY, action_object=reply_news,
            id_value=str(parent.uuid_id), key='social_update')

    def get_thread(self):
        parent = self.get_parent()
        return parent.thread.all()

    def count_thread(self):
        return self.get_thread().count()

    def count_likers(self):
        return self.liked.count()

    def get_likers(self):
        return self.liked.all()

HTML

{% load i18n %}
{% block content %}
<div class="modal fade" id="newsFormModal" tabindex="-1" role="dialog" aria-labelledby="newsFormModalTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">{% trans "Share something new!" %}</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="postNewsForm" method="post" action="" enctype="multipart/form-data">
          {% csrf_token %}
          <div class="form-group">
            <textarea id="newsInput" name="post" rows="3" class="form-control" maxlength="280"></textarea>
            <span id="newsCounter" class="pull-right">280</span>
          </div>
          <input type="file" name="myfile">
      <div class="modal-footer">
        <button type="submit" id="postNews" class="btn btn-primary">
          <i class="fa fa-paper-plane" aria-hidden="true"></i> {% trans 'Post' %}
        </button>
         <button type="button" class="btn btn-primary" data-dismiss="modal">{% trans 'Upload' %}</button>


              <button type="button" class="btn btn-default" data-dismiss="modal">{% trans 'Cancel' %}</button>
              </form>
            </div>
      </div>
    </div>
  </div>
</div>
{% endblock content %}

View.py

Dana Zholdykhairova, [29.07.18 05:48]
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic import ListView, DeleteView
from django.core.files.storage import FileSystemStorage
from bootcamp.helpers import ajax_required, AuthorRequiredMixin
from bootcamp.news.models import News
from django.core.files.storage import FileSystemStorage
from .models import News
#from uploads.core.models import Document
#from uploads.core.forms import DocumentForm


def home(request):
    documents = Document.objects.all()
    return render(request, 'core/home.html', { 'documents': documents })


def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'core/simple_upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
    return render(request, 'core/simple_upload.html')


def model_form_upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = DocumentForm()
    return render(request, 'core/model_form_upload.html', {
        'form': form
    })



class NewsListView(LoginRequiredMixin, ListView):
    """A really simple ListView, with some JS magic on the UI."""
    model = News
    paginate_by = 15

    def get_queryset(self, **kwargs):
        return News.objects.filter(reply=False)


class NewsDeleteView(LoginRequiredMixin, AuthorRequiredMixin, DeleteView):
    """Implementation of the DeleteView overriding the delete method to
    allow a no-redirect response to use with AJAX call."""
    model = News
    success_url = reverse_lazy("news:list")

def handle_uploaded_file(f):
    with open('/srv/media/data.txt', 'wb+') as dest:
        for chunk in f.chunks():
            dest.write(chunk)
@login_required
@ajax_required
def post_news(request):
    if request.method == "POST":
        my_uploaded_file = request.FILES['myfile'].read()
        handle_uploaded_file(my_uploaded_file)
        user = request.user
        post = request.POST['post']
        post = post.strip()
        if len(post) > 0 and len(post) <= 280:
            posted = News.objects.create(
                user=user,
                content=post,
            )
            html = render_to_string(
                'news/news_single.html',
                {
                    'news': posted,
                    'request': request
                })
            return HttpResponse(html)
        else:
            lenght = len(post) - 280
            return HttpResponseBadRequest(content=_(f'Text is {lenght} characters longer than accepted.'))
    else:
        return HttpResponseBadRequest(content=_('Wrong request type.'))

    '''        
                form = NewsForm(request.POST or None, request.FILES or None)
                if form.is_valid():
                    form.save()
                    html = render_to_string(
                        'news/news_single.html',
                        {
                            'form': form,
                            'request': request
                        })
                    return HttpResponse(html)
                else:
                    return HttpResponseBadRequest(content=_('Wrong request type.'))'''
    """A function view to implement the post functionality with AJAX allowing
    to create News instances as parent ones."""
    '''if request.method == 'POST':
        user = request.user
        post = request.POST['post']
        post = post.strip()
        if len(post) > 0 and len(post) <= 280:
            posted = News.objects.create(

Dana Zholdykhairova, [29.07.18 05:48]
user=user,
                content=post,
            )
            html = render_to_string(
                'news/news_single.html',
                {
                    'news': posted,
                    'request': request
                })
            return HttpResponse(html)

        else:
            lenght = len(post) - 280
            return HttpResponseBadRequest(
                content=_(f'Text is {lenght} characters longer than accepted.'))

    else:
        return HttpResponseBadRequest(content=_('Wrong request type.'))
'''

@login_required
@ajax_required
def like(request):
    """Function view to receive AJAX, returns the count of likes a given news
    has recieved."""
    if request.method == 'POST':
        news_id = request.POST['news']
        news = News.objects.get(pk=news_id)
        user = request.user
        news.switch_like(user)
        return JsonResponse({"likes": news.count_likers()})

    else:
        return HttpResponseBadRequest(content=_('Wrong request type.'))


@login_required
@ajax_required
def get_thread(request):
    """Returns a list of news with the given news as parent."""
    news_id = request.GET['news']
    news = News.objects.get(pk=news_id)
    news_html = render_to_string("news/news_single.html", {"news": news})
    thread_html = render_to_string(
        "news/news_thread.html", {"thread": news.get_thread()})
    return JsonResponse({
        "uuid": news_id,
        "news": news_html,
        "thread": thread_html,
    })


@login_required
@ajax_required
def post_comment(request):
    """A function view to implement the post functionality with AJAX, creating
    News instances who happens to be the children and commenters of the root
    post."""
    if request.method == 'POST':
        user = request.user
        post = request.POST['reply']
        par = request.POST['parent']
        parent = News.objects.get(pk=par)
        post = post.strip()
        if post:
            parent.reply_this(user, post)
            return JsonResponse({'comments': parent.count_thread()})

        else:
            return HttpResponseBadRequest()

    else:
        return HttpResponseBadRequest(content=('Wrong request type.'))


@login_required
@ajax_required
def update_interactions(request):
    data_point = request.POST['id_value']
    news = News.objects.get(pk=data_point)
    data = {'likes': news.count_likers(), 'comments': news.count_thread()}
    return JsonResponse(data)

得到实际需要上传的文件的“ multivaluedictkeyerror”错误后,在下面的图片中显示错误消息 Error Message

1 个答案:

答案 0 :(得分:1)

由于尝试从myfile获取request.FILES而引发的错误,但是request.FILES不包含myfile。 (在KeyError的情况下为dict)。

我在您的myfile中发现了view变量的一些用法,将其更改为

def simple_upload(request):
    if request.method == 'POST' and 'myfile' in request.FILES:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'core/simple_upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
    return render(request, 'core/simple_upload.html')


def post_news(request):
    if request.method == "POST" and 'myfile' in request.FILES:
        my_uploaded_file = request.FILES['myfile'].read()
        handle_uploaded_file(my_uploaded_file)
        user = request.user
        ... your code