Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters from partial form to model during save Django

I have a model with many fields, for which I am creating two partial forms

#model
class Line_Settings(models.Model):
....
    line = models.ForeignKey(Line)
    All = models.BooleanField(default=False)
    Busy = models.BooleanField(default=False)
    MOH = models.CharField(max_length=100, blank=True, null=True)
    PLAR = models.CharField(max_length=100, blank=True, null=True)
....

    def save(self, commit = True, *args, **kwargs):
       ....
#Partial model form1
class General(ModelForm):
    class Meta:
        model = Line_Settings
        fields = ('MOH','PLAR')
#Partial model form2        
class Common(ModelForm):
    class Meta:
        model = Line_Settings
        fields = ('All','Busy') 

I have overwritten the save for the Line_Settings model to do additional logic.

I need to be able to pass some parameters to the overwritten save method to use in my logic.

In my views I fill up the two partials forms with post data and can call save.

call_forwards = Common(request.POST, instance=line_settings)
general = General(request.POST, instance=line_settings)

I need to pass a parameter to the save like so:

call_forwards.save(parameter="value")
general.save(parameter="value")

I have referred to passing an argument to a custom save() method

I can get access to the parameter if I overwrite the save on my partial form.

# overwritten save of partial form
def save(self, parameter, commit=True):
     print("In save overwrite Partial form Common "+str(parameter))
     #how Can I pass this parameter to the model save overwirite?
     super(Common, self).save(commit)

From the partial form, how do I make the parameter reach my original model(Line_Settings) save overwrite?

Can this be done? Thanks in advance for reading!!

like image 207
akotian Avatar asked Oct 06 '22 18:10

akotian


1 Answers

I was able to achieve this by defining a parameter in my original models __init__ method

def __init__(self, *args, **kwargs):
    self.parameter= None
    super(Line_Settings, self).__init__(*args, **kwargs)

Then in the partial form, I could access this parameter and set it to value passed during save

 def save(self, *args, **kwargs):
     self.instance.parameter = kwargs.pop('parameter', None)
     super(Common, self).save(*args, **kwargs)

In my view I called the save as :

common = Common(request.POST, instance=line_settings)
common.save(parameter="something")
like image 151
akotian Avatar answered Oct 10 '22 02:10

akotian