How to add multiple forms to Django view if one is ChatGPT input?

  Kiến thức lập trình

I like to add two separate forms into one view what is not a big deal but I can’t find where is the stuff what makes an error and both of the forms works not. This is the first time I’m integrating ChatGPT and I’m not so familiar with fetch api.
After posting I get no error message from the http request form just not saving the data. ChatGPT form say: An error occurred. Please try again.
(I changed the names and id’s so if it ot consistent here, in my server it causes no problems)

views.py

def add_new_stuff(request, company_uuid, position_id):

    form = AddStuffFrom(request.POST)

    if request.method == "POST" :
        if 'chatGptSubmitBtn' in request.POST:
            try:
                data = json.loads(request.body)
                user_input = data.get('user_input', '')
                if user_input:
                    chatgpt_response = get_chatgpt_response(user_input)
                    return JsonResponse({'response': chatgpt_response})
                return JsonResponse({'error': 'No user input provided'}, status=400)
            except json.JSONDecodeError:
                return JsonResponse({'error': 'Invalid JSON'}, status=400)
 
        if 'stuffSubmitBtn' in request.POST:
            if form.is_valid():
                form.save()

    context = {
        'form': form,
        'company_uuid': company_uuid,
        'uuid': company_uuid,
        'position_id': position_id,
    }

    return render(request, 'stuff/add_new_stuff.html', context)

html

<form id="openai_form" method="post">
    {% csrf_token %}
        <label for="user_input" class="h5 text-primary"><i class="bi bi-robot"></i> AI</label>
        <input type="text" class="form-control" id="user_input" name="user_input" required>
        <button type="submit" id="chatGptSubmitBtn" class="btn btn-primary btn-sm my-3" id="aidaSubmitBtn"><i class="bi bi-play-circle-fill"></i> Mehet</button>
    <div class="my-3 px-2" id="response"></div>
    </form>

    <form id="independent_form" method="post">
        {% csrf_token %}
            {{ form.as_p }}
            <button type="submit" id="stuffSubmitBtn">Submit stuff</button>
    </form>


<script>
    document.getElementById('openai_form').onsubmit = async function(event) {
    event.preventDefault();
        const user_input = document.getElementById('user_input').value;
        const responseDiv = document.getElementById('response');

        try {
            const response = await fetch("{% url 'stuff:add_new_stuff' company_uuid=company_uuid position_id=position_id %}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}'
                },
                body: JSON.stringify({ user_input: user_input })
            });

            const data = await response.json();
            if (response.ok) {
            responseDiv.innerText = data.response;
            } else {
            responseDiv.innerText = 'Error: ' + data.error;
            }
        } catch (error) {
        responseDiv.innerText = 'An error occurred. Please try again.';
        } finally {
        spinner.style.display = 'none';
        }
    };

</script>

forms.py

class AddStuffFrom(forms.ModelForm):

    class Meta:
        model = Stuff
        fields = '__all__'
    
        widgets = {
            'stuff': forms.TextInput(attrs={'class': 'form-control'}),
            'grade_01': forms.TextInput(attrs={'class': 'form-control'}),
            'grade_02': forms.TextInput(attrs={'class': 'form-control'}),
            'grade_03': forms.TextInput(attrs={'class': 'form-control'}),
            'grade_04': forms.TextInput(attrs={'class': 'form-control'}),
        }

models.py

class Stuff(models.Model):
    
    def __str__(self):
        return str(self.position)

    position = models.ForeignKey(Company_positions, null=True, blank=True, on_delete=models.CASCADE)
    company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE)
    stuff = models.CharField(max_length=300, blank=True, null=True)
    grade_01 = models.CharField(max_length=500, blank=True, null=True)
    grade_02 = models.CharField(max_length=500, blank=True, null=True)
    grade_03 = models.CharField(max_length=500, blank=True, null=True)
    grade_04 = models.CharField(max_length=500, blank=True, null=True)
    datetime = models.DateTimeField(auto_now_add=True)

LEAVE A COMMENT