Updating a django form involving 2 seperate functions (template function & form specific function)

I am trying to a update a form from a separate function.

By clicking on button "Add" the existing form is updated by adding a user to the form.

Adding the user to the form works fine. However I am loosing the text input from the initial form when submitting my update.

The reason why I am using 2 functions is because I have multiple forms on the same template: each form is redirected to a specific url defined in action="{% url %}"

The usual way I use to update a form is as follows:

def function(request, id)
    instance = get_object_or_404(Model, pk=id) 
    data = Model(request.POST or None, instance = instance)

This is not working in this case because I need to provide the instance_id on the parent function, but the id parameter is provided on the function that supports the form. (child function)

I suppose there is 2 options/questions:

  1. Can I access the form_id from the parent function?
  2. Should I deal with this in the form function? and in this case how do I keep the existing text when updating form?

model

class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
     
class Model(models.Model):
    user = models.ManyToManyField(User, blank=True)
    text = models.TextField('text', blank=True)

template (main/parentfunctiontemplate.html)

{%for model in a %}
        <form action="{%url 'child-function' userprofile.id model.id%}" method="POST">
        {% csrf_token %}
        <input type="Submit"  value="Add" class="btn btn-primary custom-btn">  
        </form>
{%endfor%}

view

def parent_function(request, userprofile_id):
    a = Model.objects.filter(venue=request.user.userprofile.venue)
    updateform=ModelForm()       
    return render(request,"main/parentfunctiontemplate.html",{'updateform':updateform,'a':a})

def child_function(request, userprofile_id,model_id):
    url = request.META.get('HTTP_REFERER')
    userprofile = get_object_or_404(UserProfile, pk=userprofile_id)
    instance = get_object_or_404(Model, pk=model_id)
    updateform = ModelForm(request.POST or None, instance = instance)
    if updateform.is_valid():
        data = updateform.save(commit=False)
        data.save()
        updateform.save_m2m()
        current_model_instance = get_object_or_404(Model, id=data.id)
        current_model_instance.user.add(userprofile.id)
        return redirect(url)
    else:
        print(updateform.errors)
    return redirect('main/parentfunctiontemplate.html',{'userprofile':userprofile,'instance ':instance })

form

class ModelForm(ModelForm):
    class Meta:
        model = Model
        fields = ('text')
Back to Top