django 如果有两个带有上传表单的CBV,如何设置url?[duplicate]

fykwrbwg  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(155)

此问题在此处已有答案

The view didn't return an HttpResponse object. It returned None instead(7个答案)
18小时前关门了。
此帖子在18小时前编辑并提交审查。
我有一个上传功能。但当我试图上传文件时。我得到这个错误:

ValueError at /controlepunt140
The view main.views.view didn't return an HttpResponse object. It returned None instead.

这就是模板:用于上传pdf文件和上传excel。因此,一个模板:

<form
            class="form-inline"
            role="form"
            action="/controlepunt140"
            method="POST"
            enctype="multipart/form-data"  >
            <div class="form-group">
              {% csrf_token %} {{ form }}
              <button type="submit" name="form_pdf" class="btn btn-warning">
                Upload!
              </button>
            </div>

            <div class="form-outline">
              <div class="form-group">
                <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25">
  {{content}}</textarea
                >
              </div>
            </div>
          </form>

            <form
            class="form-inline"
            role="form"
            action="/controlepunt140"
            method="POST"
            enctype="multipart/form-data">
            <div class="form-group">
              {% csrf_token %} {{ form }}
              <button type="submit" name="form_excel"  class="btn btn- 
               warning">
                Upload!
              </button>
            </div>
            <div class="form-outline">
              <div class="form-group">
                <textarea class="inline-txtarea form-control" id="" cols="65" rows="25">
  {{content_excel}}</textarea
                >
              </div>
            </div>
          </form>

            <form
            class="form-inline"
            role="form"
            action="/controlepunt140"
            method="POST"
            enctype="multipart/form-data">
            <div class="form-group">
              {% csrf_token %} {{ form }}
              <button type="submit" name="form_excel"  class="btn btn- 
               warning">
                Upload!
              </button>
            </div>
            <div class="form-outline">
              <div class="form-group">
                <textarea class="inline-txtarea form-control" id="" cols="65" rows="25">
  {{content_excel}}</textarea
                >
              </div>
            </div>
          </form>

然后我使用两个CBV views.py:

class ReadingFile(View):
    def get(self, request):
        form = ProfileForm()
        return render(request, "main/controle_punt140.html", {
            "form": form
        })

    def post(self, request):
        filter_text = FilterText()
        types_of_encoding = ["utf8", "cp1252"]
        submitted_form = ProfileForm(request.POST, request.FILES)
        content = ''

        if request.POST.get('form_pdf') is not None:
            if submitted_form.is_valid() and request.POST:
                uploadfile = UploadFile(image=request.FILES["upload_file"])

            uploadfile.save()

            for encoding_type in types_of_encoding:
                with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
                    if uploadfile.image.path.endswith('.pdf'):
                        content = filter_text.show_extracted_data_from_file(
                            uploadfile.image.path)

                    else:
                        content = f.read()

                return render(request, "main/controle_punt140.html", {
                    'form': ProfileForm(),
                    "content": content
                })

        return render(request, "main/controle_punt140.html", {
            "form": submitted_form,

        })

class ReadingExcel(View):

    def get(self, request):
        form = ExcelForm()
        return render(request, "main/controle_punt140.html", {
            "form": form
        })

    def post(self, request):
        submitted_form = ExcelForm(request.POST, request.FILES)
        content_excel = ''

        if request.POST.get('form_excel') is not None:
            if submitted_form.is_valid() and request.POST:
                excel_file = request.FILES["upload_file"]
                excel_file.save()

                wb = openpyxl.load_workbook(excel_file)
                worksheet = wb['Sheet1']
                print(worksheet)
                excel_data = list()
                content_excel = excel_data

                return render(request, "main/controle_punt140.html",  {
                    "form": ExcelForm(),
                    "content_excel": content_excel,
                })
            else:
                print('submitted form is not valid check it.')
        else:
            print('form-excel value is not in request.POST.get()')
        return render(request, "main/controle_punt140.html", {
            "form": submitted_form,
            "content_excel": content_excel,
        })

和forms.py:

class ProfileForm(forms.Form):
    upload_file = forms.FileField()

class ExcelForm(forms.Form):
    upload_file = forms.FileField()

问题:如何解决?
我的urls.py是这样的:

urlpatterns = [  
    path('', views.starting_page, name='starting_page'),
    path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140'),
    path('controlepunt140', views.reading_excel.as_view(), name='controlepunt140')
]

但是如果我用views.ReadingFile注解路径,它就能工作。当然我希望它们都能工作。

mqkwyuun

mqkwyuun1#

看起来有些if条件无效,所以视图没有返回HttpResponse,或者问题也可能是验证后没有重定向(即submitted_form.is_valid()),所以尝试下面的视图:

def post(self, request):
    submitted_form = ExcelForm(request.POST, request.FILES)
    content_excel = ''

    if request.POST.get('form_excel') is not None:
        if submitted_form.is_valid() and request.POST:
            excel_file = request.FILES["upload_file"]
            excel_file.save()

            wb = openpyxl.load_workbook(excel_file)
            worksheet = wb['Sheet1']
            print(worksheet)
            excel_data = list()
            content_excel = excel_data

            return render(request, "main/controle_punt140.html",  {
                "form": ExcelForm(),
                "content_excel": content_excel,
            })
        else:
            print('submitted form is not valid check it.')
    else:
        print('form-excel value is not in request.POST.get()')
    return render(request, "main/controle_punt140.html", {
        "form": submitted_form,
        "content_excel": content_excel,
    })

编辑

问题是两个视图的url相同,甚至名字也相同,所以Django选择了第一个视图ReadingFile,你在问题中也指定了But if I comment the path with views.ReadingFile it works.

相关问题