Django мультимодельформ + Inlineformset + updateview - PullRequest
0 голосов
/ 23 января 2020

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

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

Формы

class CompanyManagementForm(forms.ModelForm):    
entitynameoptional1=forms.CharField(max_length=200, required=False, label='COMPANY Name (Optional):')
entitynameoptional2=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', 'entitynameoptional1', 'entitynameoptional2', 'jurisdiction', 'entitysubtype', 'clientcategory', 'managedbyamicorp', 'origin', 'reasonfortransferin', 'previousserviceprovider')
    labels ={'entitynamepreferred' : 'COMPANY Name (Preferred):', 
    'entitynameoptional1':'COMPANY Name (Optional):', 
    'entitynameoptional2':'COMPANY Name (Optional):', 
    'jurisdiction':'Jurisdiction',         
    'entitysubtype': ' Entity Sub-type', 
    'clientcategory': ' Client category', 
    'managedbyamicorp': ' Managed by Amicorp', 
    'origin': 'Origin', 
    'reasonfortransferin': ' Reason for transfer in', 
    'previousserviceprovider': ' Previous service provider'} 
    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', 'entitynameoptional1', 'entitynameoptional2', 'jurisdiction', 'entitysubtype', 'clientcategory', 'managedbyamicorp', 'origin', 'reasonfortransferin', 'previousserviceprovider'
        ))
class TransactionProfileform(forms.ModelForm):
class Meta:
    model=TransactionProfile
    fields =('sourceoffund', 'sourcedetaileddescription', 'expectedtransactioninentity1', 'expectedtransactioninentity2', 'expectedtransactioninentity3','transactiondetaileddescription')
#entityid,

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', 'expectedtransactioninentity2', 'expectedtransactioninentity3','transactiondetaileddescription'
        ))
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):
base_forms = {
    'CompanyManagement': CompanyManagementForm,
    'TransactionProfile': TransactionProfileform,           
}
def dispatch_init_instance(self, name, instance):
    print('-------------name-----------------', name)
    if name == 'CompanyManagement':
        return instance
    return super(CompanyManagementMultiform, self).dispatch_init_instance(name, instance)

Просмотр

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
...