Home > database >  Django, problem with render request: "The view main.views.licz didn't return an HttpRespon
Django, problem with render request: "The view main.views.licz didn't return an HttpRespon

Time:07-22

I'am trying to do a website and I have problem with uploading the file. On admin site I can upload and import any file but when I create view, I get this: "The view main.views.licz didn't return an HttpResponse object. It returned None instead." Here is the code from main.models:

class Plik(models.Model):
    file = models.FileField(upload_to='uploads/')

Code from forms.py:

class upload(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()

And code from views.py:

def licz(request):
    if request.method == "POST":
        form = upload(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("main/licz.html", {"form":form})
        else:
            form = Plik()
        return render(request, "main/licz.html", {"form":form})

Plz I am trying to solve this like 5 days...

CodePudding user response:

def licz(request):
    if request.method == "POST":
        form = upload(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("main/licz.html", {"form":form})
        else:
            form = Plik()
        return render(request, "main/licz.html", {"form":form})

    # if request is GET, python will execute this part of the function

Your livz function does not return anything on a GET request. If no return statement is given, Python will return None.

The return render(...) is only executed on a POST request (when the form is submitted) with invalid form.

You need to also render your page on other request method. A typical form view should look like the following (pay attention to the indent):

def form_view(request):
    if request.method == 'POST':
        form = MyForm(data=request.POST)
        if form.is_valid():
            # do stuff with the form
            return HttpResponseRedirect('/success-url')
    else:
        form = MyForm()

    return render('my-template', {'form': form})

Pay attention to your conditions (if/else/...) and make sure your page return a response in every possible path the code execution takes.

CodePudding user response:

def licz(request):
    if request.method == "POST":
        form = upload(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("main/licz.html")
        else:
            form = Plik()
    return render(request, "main/licz.html", {"form":form})
  • Related