Maddie Graham
Maddie Graham

Reputation: 2177

Editing the values ​of two tables from one view. Django

In the Parent table, I have many objects. The user has a form in which he can choose one of the Parent objects. It looks like this:

class ChildForm(forms.ModelForm):
    class Meta:
        model = OrderingMassage
        fields = ('parent',
                  'name')

Now I would like to get for each object 'parent' selected by the user in the Parent table, the 'on_off button' value changed to False. How can I recover it? What can I use? Can I do it in my view using one form?

For example:

models.py

class Parent(models.Model):
    name = models.CharField(max_length=15)
    on_off_button = models.BooleanField(deflaut=True)

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
    name = models.CharField(max_length=15)

views.py

if request.method == 'POST' and 'child_btn' in request.POST:
    child_form = ChildForm(request.POST)
    if child_form.is_valid():
        child = child_form.save(commit=False)
        name = child_form.cleaned_data['name']
        parent = child_form.cleaned_data['parent']
        # Can I add an element here that will change the value parent.id on False
        child.name = name
        child.parent = parent
        child.save()
else:
    child_form = ChildForm()

Any help will be appreciated.

Upvotes: 0

Views: 218

Answers (1)

Sanip
Sanip

Reputation: 1810

In your views you can do something like:

if request.method == 'POST' and 'child_btn' in request.POST:
    child_form = ChildForm(request.POST)
    if child_form.is_valid():
        child = child_form.save(commit=False)
        name = child_form.cleaned_data['name']
        parent = child_form.cleaned_data['parent']

        child.name = name
        child.parent = parent
        child.save()

        #get the parent object related to the parent selected by the user
        parent = Parent.objects.get(id=parent.id)
        parent.on_off_button = False
        parent.save()

        #or can you try this method to check
        parent.on_off_button=False
        parent.save()

else:
    child_form = ChildForm()

Upvotes: 1

Related Questions