0

I am working in django 1.8 project, and I have a model called company and I have used the generic view to do simple CRUD over this model.

I have a detail view, which renders the detail of the company model in a template name called company/company_detail.html

The detail page is rendered with the company object information. Along with the company object info, I have added a form in this detail page, and I want to process the form data with this DetailView method. I tried to use the post method of CompanyDetailView but, it doesn't work, when I try to navigate the CompanyDetailView page, the post method executed automatically which I don't want, What I want is execute the post method of CompanyDetailView when the post request came to this CompanyDetailView class.

Here is the CompanyDetailView

class CompanyDetailView(DetailView):
    model = Company
    template_name = 'company/company_detail.html'
    context_object_name = 'company'

    def post(self, request, *args, **kwargs):
       price_value = request.POST.get('paid-value')
       print(price_value)
       return render(request, 'company/company_detail.html', {'company':self.context_object_name}

The company_detail.html is

<body>
 {% block main %}
   {{company.name}} 
  <form method="post" action=""> 
   Paid Value: <input type="number" name="paid-value", required>
   <button type="submit" name="submit" value="pay">
  </form>
 {% endblock main %}
</body>

urls.py file

url(r'company/(?P<pk>\d+)/$', CompanyDetailView.as_view(), name="company"),
shining
  • 1,049
  • 16
  • 31
  • "When I try to navigate the CompanyDetailView page, the post method executed automatically." Are you sure? I don't see how that would be possible. More generally though it probably isn't a good idea to POST to the same view - use a separate `FormView` instead that redirects back to the detail view after posting. – solarissmoke Jun 24 '16 at 04:54
  • @solarissmoke I am sure, the post method executed automatically, When I call the url of detail view. yes, I can create another function based view and map to a URL, but I don't want to make another complication, by setting another view and modelForm. – shining Jun 24 '16 at 04:57

0 Answers0