Pre-populate HTML form table from database using Django

前端 未结 3 1384
太阳男子
太阳男子 2021-02-11 02:24

I have a class-based view (IndexView at views.py) that shows a table with all the data stored in the database. This view is rendered in index.html<

3条回答
  •  -上瘾入骨i
    2021-02-11 03:06

    what about using generic from django.views.generic.edit import UpdateView straight on model?

    https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/#updateview

    views.py:

    from django.forms import ModelForm, CharField, Textarea
    from django.urls import reverse_lazy
    from django.views.generic import UpdateView
    
    from demo.models import Item
    
    
    class ItemForm(ModelForm):
        description = CharField(widget=Textarea)
    
        class Meta:
            model = Item
            fields = ['code', 'amount']
    
        def save(self, commit=True):
            item = super(ItemForm, self).save(commit=commit)
            item.code.description = self.cleaned_data['description']
            item.code.save()
    
        def get_initial_for_field(self, field, field_name):
            if field_name == 'description':
                return self.instance.code.description
            else:
                return super(ItemForm, self).get_initial_for_field(field, field_name)
    
    
    class ItemUpdateView(UpdateView):
    
        form_class = ItemForm
        model = Item
    
        def get_success_url(self):
            return reverse_lazy('item-detail', kwargs={'pk': 1})
    

    urls.py

    from django.conf.urls import url
    from django.contrib import admin
    from django.urls import path
    
    
    from demo.views import ItemUpdateView
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        path(r'items//', ItemUpdateView.as_view(), name='item-detail')
    ]
    

    /templates/demo/item_form.html

    {% csrf_token %} {{ form.as_p }}

    If something regarding settings or config is unclear please refer to the repo with demo: https://github.com/andilabs/cbv

    UPDATE

    added modelformset producing what you need in ListView

    from django.forms import modelformset_factory
    
    
    class ItemListView(ListView):
        model = Item
    
        def get_context_data(self, **kwargs):
            data = super(ItemListView, self).get_context_data()
            formset = modelformset_factory(Item, form=ItemForm)()
            data['formset'] = formset
            return data
    

    this just displays data in forms, you have take care of rest.

提交回复
热议问题