Search code examples
javascriptvalidationdjango-viewsfetch-apirender

Unable to render() in django views when calling backend url using javascript fetch


I am using javascript for form validation and the calling the backend api using fetch the backend is hanlded by django then the view associated by the api is rendering a page with some context but the response is going back the fetch instead of returning the html page so i want to render the page with some context how can i do it

javascript form validation

try {
        const response = await fetch("/save_dependent", { // Ensure you replace "/save_dependent" with your actual endpoint
            method: "POST",
            headers: {
                "X-CSRFToken": document.querySelector('input[name="csrfmiddlewaretoken"]').value, // Pass the CSRF token in the request headers
                // Do not set 'Content-Type' manually; let the browser handle it for multipart/form-data boundary
            },
            body: formData,
        });
        if (response.ok) {
            let data = await response.text(); 
            console.log('Server Response:', data);

        } else {
            // Handle HTTP error responses (e.g., 400, 401, 403, 404, 500)
            console.error('Server responded with non-OK status:', response.status);
        }
        } catch (error) {
        console.error('Error:', error);
    }

views.py

@login_required(login_url='auth/signin')
def save_dependent(request):
    # print('request.data: ',request.data)
    print("POST data:")
    for key, value in request.POST.items():
        print(f"{key}: {value}")
    if request.method == 'POST':
        uploaded_file = request.FILES.get('dependent_docs')
        print('uploaded_file ',uploaded_file)
        if uploaded_file:
            # Handle file processing
            print(f"Received file: {uploaded_file.name}")
            save_path = os.path.join(SETTINGS.BASE_DIR, 'static', 'assets', 'img', 'beyond_border_dependents_doc', uploaded_file.name)
            try:
                # Writing the uploaded file to the specified directory
                with open(save_path, 'wb+') as destination:
                    for chunk in uploaded_file.chunks():
                        destination.write(chunk)
                print('returning....')
                return render(request, 'nhcp_registration_test.html',{'dependent_saved':'successs'})
                # return HttpResponse("File uploaded successfully")
            except Exception as e:
                # Handle exceptions that occurred during file upload
                print(f"Failed to upload file. Error: {e}")
                return HttpResponse("Failed to upload file.", status=500)
        else:
            print('in else of uploaded_file')
            return render(request, 'nhcp_registration.html',{'dependent_saved':'successs'})
    print('at last return')    
    return render(request, 'nhcp_registration_test.html')

i want to the view to render a html page with some context but as i am calling the backend api using fetch the output of view is being returned to the response of the fetch but i want to render the page with the context

I tried to render the output of the view( which is a html page with context) using document.documentElement.innerHTML = data; but it is not working and i don't think it is the best way so how can i render the html page with the context which is reutrned by the view


Solution

  • I solved this using by action, method attributes of the html form and by using document.getElementById("form_id").submit(); we will metion what backend url to hit in the action attribute of the form, also mention method='POST'

    <form action="/backend_url" id="form_id" method="post">

    and I am using parsleyjs for the form validation, it has a onFinished event when the form is submitted/finished in that event i gave a callback function which does the form validation and if the form validation is successful then form is submitted using

    document.getElementById("form_id").submit();

    by doing this i avoided using the fetch() by which i am able to achieve render()