skip to Main Content

I am trying to update a django form according to user clicks. The user is allowed to add more form tags on the DOM by clicking a button, add a value to it, and submit when the user is done.

I have used modelForm to build the initial part of the form which was rendered in the template. But when the form is submitted it only shows values that are part of the ReportForm class which inherits forms.ModelForm.

Here is my report class:

class ReportForm(forms.ModelForm):

date_resolved = forms.DateField(widget=forms.DateInput(attrs={
    'name': 'date_resolved',
    'type': 'date',
}), label="Date resolved (ignore if not):")

bias_score = forms.IntegerField(widget=forms.NumberInput(attrs={
    'type': 'range',
    'width': '100%',
    'value':0,
    'min': 0,
    'max': 10,
    'step': 1,
    'style': "padding: 0;"
}), label="Bias Score (between 0 and 10)")


class Meta:
    model = Reports
    fields = ['date_resolved', 'tags', 'bias_score']

and this is what the report class looks like

class Reports(models.Model):

user = models.ForeignKey(User, on_delete=models.CASCADE)
conversation = models.ForeignKey(Conversations, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tags, null=True, blank=True)
bias_score = IntegerRangeField(min_value=1, max_value=10)
resolved = models.BooleanField(default=False)
date_resolved = models.DateField(blank=True, null=True)
date_added = models.DateField(auto_now_add=True)

The javaScript is bit long but here is the most importtant part:

function create_tags(){
let label_text_content = null
if (IS_PROMPT == true){
    IS_PROMPT = false
    INPUT_COUNTER +=1
    label_text_content = 'Prompt:'
    
    prompt_response = `${label_text_content}_${INPUT_COUNTER}`
    // console.log("is prompt true", label_text_content, "prompt response", prompt_response);
    
}
else {
    label_text_content = 'Response:'
    IS_PROMPT = true
    prompt_response = `${label_text_content}_${INPUT_COUNTER}`
    // console.log("is prompt false", label_text_content, "prompt response", prompt_response);
}
let div_row = document.createElement('div')
div_row.classList.add('form_row', 'conv_row')

let div_label = document.createElement('div')
div_label.classList.add('tag_label')
let label_for = document.createElement('label')
label_for.id = prompt_response
label_for.textContent = label_text_content
div_label.appendChild(label_for)

let div_tag = document.createElement('form_tag')
div_tag.classList.add('form_tag')
let text_area = document.createElement('textarea')
text_area.id = `${prompt_response}`
div_tag.appendChild(text_area)



return [div_label, div_tag, div_row]

}

function create_message(){
let tags = create_tags()
div_label = tags[0]
div_tag = tags[1]
div_row = tags[2]
    
div_row.appendChild(div_label)
div_row.appendChild(div_tag)
conversations.appendChild(div_row)

}

How do I include the new tags added via javascript to the reportform and make it show up in the view function when I print(request.POST).

2

Answers


  1. Chosen as BEST ANSWER

    I used a hidden field to collect the user inputs and I was able to see this in request.POST. Thanks viaTech for reaching out.


  2. Here is the code I used for the work around the problem. I have a hidden text area in the form and once the user submits the form, I will process the prompt/reponse values and use it to replace the value of the text area.

    submit_report_form.addEventListener('click', (e)=> {
    e.preventDefault()
    let id_conv_holder = document.querySelector('#id_conv_holder')
    let conversations = document.querySelector('#conversations').childNodes
    let conversations_arr = [...conversations].slice(1,)
    let total_in_prompts = document.querySelectorAll('.input_prompts')
    /**
     * @todo total_in_prompts to check if the user has provided 
     * prompt without response or vice versa
     * this can be infered if the total_in_prompts is not even
     * i.e not divisble by 2.
     */
    // console.log("total_in_prompts", total_in_prompts.length);
    let cur_val_load = {}
    for (let i=0; i<conversations_arr.length; i++){
        let cur_label_node = conversations_arr[i].childNodes[0].childNodes[0].id.toLowerCase()
        let cur_tag_node = conversations_arr[i].childNodes[1].childNodes[0].value.toLowerCase()
        let cur_tag_node_id = conversations_arr[i].childNodes[1].childNodes[0].id.toLowerCase()
        cur_val_load[`${cur_tag_node_id}`] = cur_tag_node
       
    }
    
    id_conv_holder.value = JSON.stringify(cur_val_load)
    
    report_form.submit()
    

    })

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search