You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django 2.0中用TemplateView和ModelForm上传文本文件

Hey there! Let's work through your file upload issue with Django 2.0 and TemplateView. I spotted a few key issues in your code that are keeping the upload from working correctly—let's fix them one by one.

1. Fix Form Handling in SummerizerView

Your current view logic has two main problems: form initialization is incorrect for GET requests, and the POST method doesn't properly validate the submitted form. Here's the corrected views.py:

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from .forms import FileUploadForm

class HomePageView(TemplateView):
    template_name = 'Aamir/index.html'

class SummerizerView(TemplateView):
    template_name = 'Aamir/summrizer.html'

    def post(self, request, *args, **kwargs):
        # Initialize form with POST data and uploaded files
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            print('yes done')
            form.save()
            # Optional: Redirect to a success page or back to the form
            # return HttpResponseRedirect('/summerizer/')
        # Pass the (possibly invalid) form back to the template
        return self.render_to_response(self.get_context_data(form=form))

    def get_context_data(self, **kwargs):
        context = super(SummerizerView, self).get_context_data(**kwargs)
        # Use the passed form (for invalid POST) or create a new one for GET
        context["form"] = kwargs.get('form', FileUploadForm())
        return context

2. Correct the save Method in FileUploadForm

Your form's save method has two critical errors: you're referencing the model instead of the form in super(), and you're trying to update a non-existent name field. Here's the fixed forms.py:

from django import forms
from .models import FileUpload

class FileUploadForm(forms.ModelForm):
    class Meta:
        model = FileUpload
        fields = ('upload_file',)
        widgets = {
            'upload_file': forms.FileInput(attrs={'class': 'form-control', 'accept': 'text/plain', 'id':'fupload', 'name':'fupload', 'placeholder': 'Browse Files' }, ),
        }
        error_messages = {
            'upload_file': {
                'required': "No file selected!",
            },
        }

    def save(self, commit=True):
        # Reference the form class in super(), not the model
        instance = super(FileUploadForm, self).save(commit=False)
        if commit:
            instance.save()  # No need for update_fields since we're saving the correct field
        return instance

3. Fix the File Upload Path in Your Model

Your upload_to path is redundant with your MEDIA_ROOT setting, which will cause files to save to media/media/%Y/%m/%d/ instead of the intended media/%Y/%m/%d/. Update models.py:

from django.db import models

class FileUpload(models.Model):
    upload_file = models.FileField(upload_to='%Y/%m/%d/')

4. Add Media URL Configuration (Critical for Accessing Uploads)

In your project's urls.py, add configuration to serve media files (only for DEBUG mode):

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', include('Aamir.urls')),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Optional: Switch to FormView for Cleaner Code

Django's FormView is designed specifically for form handling and will simplify your code. If you want to use it instead of TemplateView, rewrite SummerizerView like this:

from django.views.generic.edit import FormView
from .forms import FileUploadForm

class SummerizerView(FormView):
    template_name = 'Aamir/summrizer.html'
    form_class = FileUploadForm
    success_url = '/summerizer/'  # Redirect here after successful upload

    def form_valid(self, form):
        form.save()
        print('yes done')
        return super().form_valid(form)

Final Checks

  • Make sure the media folder exists in your project root and has read/write permissions
  • Test with a plain text file (your form restricts uploads to text/plain)
  • Check the form error messages on the page—your template already displays them, so you'll see why uploads fail if they do

内容的提问来源于stack exchange,提问作者user3626203

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:27:28