Home > database >  Splitting one field from model into two form input fields on django update view
Splitting one field from model into two form input fields on django update view

Time:06-17

I have this customer model with only one address field.

class PullingCustomer(models.Model):
    code = models.CharField(verbose_name='Code', max_length=10, primary_key=True)
    name = models.CharField(verbose_name='Customer', max_length=255, blank=False, null=False)
    address = models.CharField(verbose_name='Address', max_length=255, blank=False, null=False)
    city = models.CharField(verbose_name='City', max_length=25, blank=True, null=True)

def __str__(self):
    cust = "{0.name}"
    return cust.format(self)

but on my form.py, I split it into two input, address 1 and address 2.

class PullingCustomerForm(ModelForm):
    address1 = forms.CharField(max_length=155)
    address2 = forms.CharField(max_length=100)
    def __init__(self, *args, **kwargs):
        super(PullingCustomerForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            ....
            Row(
                Column('address1', css_class = 'col-md-12'),
                css_class = 'row'
                ),
            Row(
                Column('address2', css_class = 'col-md-8'),
                Column('city', css_class = 'col-md-4'),
                css_class = 'row'
                ),
            ....
    class Meta:
        model = PullingCustomer
        fields = '__all__'

Then I combine them again on view.py so I can save it.

class PullingCustomerCreateView(CreateView):
    form_class = PullingCustomerForm
    template_name = 'pulling_customer_input.html'

    def form_valid(self, form):
        address1 = form.cleaned_data['address1']
        address2 = form.cleaned_data['address2']
        temp_form = super(PullingCustomerCreateView, self).form_valid(form = form)
        form.instance.address = str(address1)   ', '   str(address2)
        form.save()
        return temp_form

Since I want to use the same form layout on my update view, I need to split the address into two again. What is the best method to do that?

class PullingCustomerUpdateView(UpdateView):
    model = PullingCustomer
    form_class = PullingCustomerForm
    template_name = 'pulling_customer_update.html'

CodePudding user response:

I believe what you are asking for may be covered by MultiWidget. I haven't ever written one, so I won't attempt to expand on this.

Alternatively, don't use the address field in a ModelForm (UpdateView). Use fields= to exclude address and add address1 and address2 to the form. You'll combine them in form_valid much as in your CreateView

    def form_valid(self, form):
        address1 = form.cleaned_data['address1']
        address2 = form.cleaned_data['address2']
        obj = form.save( commit=False)
        obj.address = str(address1)   ', '   str(address2)
        obj.save()

You'll also need some code to get the current address and use it to supply initial values for the form's address1 and address2. Using UpdateView, you would subclass get_initial. I think:

def get_initial( self)
    initial = super().get_initial()
    address = self.object.address
    # split address1, address2 from address in whatever way is appropriate
    # for example, if you store with a newline \n separating them
    address1, address2 = address.split('\n', maxsplit=1) 
    initial['address1'] = address1
    initial['address2'] = address2
    return initial
  • Related