Home > Back-end >  Trouble getting a Django Form to render
Trouble getting a Django Form to render

Time:08-11

Wondered if someone could help me with what I am doing wrong.

I wish to present an order form in Django where a customer will only ever fill in an order, they will never need to retrieve an existing order. So I think I only need a POST method and no GET method.

When I try to render a url with a form, I get a 405 response.

In my views.py file where I think I am making a mistake I have:

class RequestReport(View):
    def post(self, request, *args, **kwargs):
        form = CustomerOrderForm(data=request.POST)

        if form.is_valid():
            form.save()

        return render(
            "order.html",
            {
                "form": CustomerOrderForm()
            }
        )

And in my app urls file I have:

urlpatterns = [
    path('', views.RequestHome.as_view(), name='home'),
    path('order', views.RequestReport.as_view(), name='order'),
    path('blog', views.RequestBlog.as_view(), name='blog'),
    path('<slug:slug>/', views.PostDetail.as_view(), name='post-detail'),
]

And finally in my order.html file I have:

<form action="" method="post">
    {%  csrf_token %}

    {{ form.as_p }}

    <input type="submit" value="Submit" >
</form>

I know that the Customer Order Form is fine because if I insert this in my view it renders correctly

class RequestReport(CreateView):
    form_class = CustomerOrderForm
    template_name = 'order.html'
    success_url = "about"

But I want to be able to post the form.

CodePudding user response:

You still need to reach the form i.e. to "go" to the url where this form is without submitting it so that would be the get request

CodePudding user response:

405 is a Method Not Allowed error. Since you are making a get request when you go to /order, and your view hasn't implemented a get method, it results in a 405 error.

class RequestReport(View):
    def post(self, request, *args, **kwargs):
        form = CustomerOrderForm(data=request.POST)

        if form.is_valid():
            form.save()

        return redirect("somewhere else")

    def get(self, request, *args, **kwargs):
        return render(
            request,
            "order.html",
            {
                "form": CustomerOrderForm()
            }
        )

  • Related