Gaius G D'cruz
Gaius G D'cruz

Reputation: 63

Populate form values from database Django

I am trying to fetch data from the database to update and save. I can add the data. Since I am trying to do this in class view I don't know how to use generic. Update view and grab the entry by the id. Here is the FormView I use to submit the data

class CompanyView(generic.FormView):
    form_class = CompanyForm
    template_name = 'company/company.html'
    
    success_url = '/company'

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)

I listed the details by adding an edit button to each entry and wrote a view like the same one but stuck with populating the data with the corresponding id.

How can I modify this to make the edit?

Upvotes: 1

Views: 944

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

If you specify a URL pattern that contains a field named pk:

from app_name.views import CompanyUpdateView

urlpatterns = [
    path('edit/<int:pk>/', CompanyUpdateView.as_view(), name='company-update')
]

Then you can work with an UpdateView that will make updates to the item with the primary key:

from django.views.generic import UpdateView

class CompanyUpdateView(UpdateView):
    model = Company
    form_class = CompanyForm
    template_name = 'company/company.html'
    success_url = '/company'

This view will fetch the relevant Company from the database, populate the form with the data, and when a POST request is made, update the corresponding Company.

Upvotes: 2

Related Questions