djangomultimodelform с Inlineform, используя пакет django -multform - PullRequest
0 голосов
/ 25 января 2020

У меня проблема с обработкой Updateview в django. Мой дизайн содержит 2 модели и один Inlineformset. Это представление будет добавлено с большим количеством моделей и наборов inlineform, если это работает.

Мой createview работает нормально. Но Updateview выдает прикрепленную ошибку error image . 1) Любая идея, почему это вызывает. 2) Любой лучший способ обрабатывать несколько форм и несколько строк вместе для операций CRUD

Формы

class CompanyManagementForm(forms.ModelForm):    
entitynamepreferred=forms.CharField(max_length=200, required=False, label='COMPANY Name (Optional):')
clientcategory=forms.ModelChoiceField(keyword.objects.filter(keywordtype = 'CLIENT_CATEGORY'), required=False) 
class Meta:
    model=EntityList
    fields =('entitynamepreferred', 'clientcategory')
    labels ={'entitynamepreferred' : 'COMPANY Name (Preferred):', 
    'clientcategory': ' Client category', 
    widgets = {
    'entitynamepreferred': forms.TextInput(attrs={'class':'form-control'}),  } 

def __init__(self, * args, **kwargs):
    super().__init__(*args, **kwargs)
    self.helper = FormHelper()
    self.helper.form_class = 'form-horizontal'
    self.helper.label_class = 'col-lg-4'
    self.helper.field_class = 'col-lg-8'
    self.helper.layout = Layout(
        Fieldset(
            'first arg is the legend of the fieldset',
            'entitynamepreferred', 'clientcategory' ))

class TransactionProfileform(forms.ModelForm):  # this has a relationship with CompanyManagementmodel above
class Meta:
    model=TransactionProfile
    fields =('sourceoffund', 'sourcedetaileddescription', 'expectedtransactioninentity1')

def __init__(self, * args, **kwargs):
    super().__init__(*args, **kwargs)
    self.helper = FormHelper()
    self.helper.form_class = 'form-horizontal'
    self.helper.label_class = 'col-lg-4'
    self.helper.field_class = 'col-lg-8'
    self.helper.layout = Layout(
        Fieldset(
            'first arg is the legend of the fieldset',
            'sourceoffund', 'sourcedetaileddescription', 'expectedtransactioninentity1'        ))

class Roleform(forms.ModelForm):
class Meta:
    model=Roles
    fields = ('personrole', 'personname')
    exclude = ()     
Rolesformset = inlineformset_factory(EntityList, Roles, form= Roleform, fields = ('personrole', 'personname'), extra=1)

class CompanyManagementMultiform(MultiModelForm):  # its a multimodelfrom from django-multiform and not from better form packages
base_forms = {
    'CompanyManagement': CompanyManagementForm,
    'TransactionProfile': TransactionProfileform,           
}

Представление

from django.shortcuts import render, render_to_response
from django.views import View
from django.views.generic import TemplateView, ListView, DetailView

from django.views.generic.edit import CreateView, DeleteView, UpdateView, BaseDetailView

from .models import EntityList, Roles
from .forms import CompanyManagementForm , TransactionProfileform, CompanyManagementMultiform, Roleform , Rolesformset

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from django.forms import inlineformset_factory
from django.db import transaction

class EntityListView(LoginRequiredMixin, ListView):
    model=EntityList
    template_name= "EntityInformation\companymanagementlist.html"

class EntityCreateView(CreateView):
    form_class=CompanyManagementMultiform
    template_name = 'EntityInformation/newcompanymanagement.html'
    success_url = '/entityinformation/entitylist'

    def get_context_data(self, **kwargs):
        data= super(EntityCreateView1, self).get_context_data(**kwargs)

        Rolesformset = inlineformset_factory(EntityList, Roles, fields=('personrole', 'personname') )
        formset  = Rolesformset()
        data['formset']   = formset    
        return data        

    def form_valid(self, form):
        context = self.get_context_data()
        formset  = Rolesformset(self.request.POST)
        CompanyManagement =form['CompanyManagement'].save(commit=False)
        TransactionProfile=form['TransactionProfile'].save(commit=False)
        CompanyManagement.entitytype='Company'
        entity = form['CompanyManagement'].save()
        TransactionProfile.entityid = entity
        form['TransactionProfile'].save()

        if self.request.POST:          
            formset  = Rolesformset(self.request.POST, instance=entity)        
        if formset.is_valid():
            formset.save()

        return super(EntityCreateView1, self).form_valid(form)

class EntityUpdateView1(UpdateView):
    model=EntityList
    form_class=CompanyManagementMultiform
    pk_url_kwarg= 'entityid'
    #template_name = 'EntityInformation/newcompanymanagement.html'
    success_url = '/entityinformation/entitylist'

    def get_context_data(self, **kwargs):
        data =super(EntityUpdateView1, self).get_context_data(**kwargs)
        if self.request.POST:
            data['formset'] = Rolesformset(self.request.POST, instance=self.object)
            data['CompanyManagement'] = CompanyManagementForm(self.request.POST, instance=self.object)
            data['TransactionProfile'] = TransactionProfileform(self.request.POST, instance=self.object)
        else:
            data['formset'] = Rolesformset(instance=self.object)
            data['CompanyManagement'] = CompanyManagementForm(instance=self.object)
            data['TransactionProfile'] = TransactionProfileform(instance=self.object)
        return data

    def form_valid(self, form):
        formset  = Rolesformset(self.request.POST, instance=self.object)
        CompanyManagement =form['CompanyManagement'].save(commit=False)
        TransactionProfile=form['TransactionProfile'].save(commit=False)
        entity = form['CompanyManagement'].save()
        form['TransactionProfile'].save()

        if self.request.POST:          
            formset  = Rolesformset(self.request.POST, instance=self.object)        
        if formset.is_valid():
            formset.save()        
        return super(EntityCreateView1, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(EntityUpdateView1, self).get_form_kwargs()
        kwargs.update(instance={'CompanyManagement': self.object,'TransactionProfile': self.object.TransactionProfile })
        return kwargs

Мой createview прекрасно работает там, где есть updateview не работает.

...