FileField不上传文件

时间:2018-02-01 15:45:39

标签: python django

请告诉我任何建议。我会真的很欣赏一切。 每当我成功通过使用基于django的Web应用程序上传字段的整个流程时,什么都不会发生。正在将适当的记录插入到数据库中,但是文件本身不会被复制到服务器的文件系统中。

models.py

from django.db import models
from django.forms import ModelForm
from .choices import *
from .validators import validateExtensionOfTheFile
from django.contrib.auth.models import User

class MusicFile(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    image = models.FileField(upload_to="music_images/%Y/%m/%d", null=True, blank=True, validators=[validateExtensionOfTheFile])

forms.py

from django import forms
from .choices import *
from .models import MusicFile

class MusicFileForm(forms.ModelForm):
    class Meta:
        model = MusicFile
        fields = '__all__'
        exclude = ('owner')

    def __init__(self, *args, **kwargs):
        super(MusicFileForm, self).__init__(*args, **kwargs)
        self.fields['image'].required = False

views.py

@login_required
def new_upload(request):
    if request.method == 'POST':
        form = MusicFileForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.owner = User.objects.get(username=request.user.username)
            post.save()
            return HttpResponseRedirect('/success/confirmed/')
    else:
        form = MusicFileForm()
    return render(request, 'new_upload.html', {'form': form})

new_upload.html

{% extends 'base.html' %}

{% block content %}
<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary btn-block">Save</button>
</form>
{% endblock %}

@EDIT

setting.py:

TEMPLATES = [
    {
        ...
        ...
        ...
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
            ],
        },
    },
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

urlpatterns = [...
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

@edit 最近提到的代码更改,但它仍然无法正常工作。 无论如何,我已经将正在发送到服务器的POST请求记入帐户。 它以这样的方式制定:

csrfmiddlewaretoken=qDI7hZCzJYkqDSDnCCw3v3dG274Xb1NiYGWAMZhjgZxe4G3TXtY6EUmgtvjYLwOF&title=asdasd&image=Stromae+-+Alors+On+Danse+%28Dubdogz+Remix%29+%28Bass+Boosted%29.jpg

我不确定这个是否正确。 难道它不是以multipart / form-data的形式出现的?

3 个答案:

答案 0 :(得分:0)

嗯,想要测试一切,所以我提出了以下想法:

class UploadMusicFile(LoginRequiredMixin, CreateView):
    model = MusicFile
    success_url = '/success/confirmed/'
    template_name = 'new_upload.html'
    form_class = MusicFileForm

    # @login_required
    def form_valid(self, form):
        # result = add(2,2)
        form.instance.owner = self.request.user
        print(str(form.instance.image))
        print(str(form.instance.image.url))

这导致:

ValueError at /upload/

The 'image' attribute has no file associated with it.

答案 1 :(得分:0)

我正在推荐错误的模板名称。在配置urlpatterns的过程中犯了错误。 感谢所有花时间解决这个问题的人。

答案 2 :(得分:-1)

我不明白为什么它不能在您的fbv中运行,但您可以尝试使用基于类的视图:

class UploadMusicFile(LoginRequiredMixin, CreateView):
    model = MusicFile
    success_url = '/success/confirmed/'
    template_name = 'new_upload.html'
    form_class = MusicFileForm

    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super(UploadMusicFile, self).form_valid(form)