HELP ME WITH MY PROBLEM WITH PYTHON AND DJANGO

Hi everyone,

I’m having trouble connecting to the HubSpot API using the following code:

Views.py

from django.shortcuts import render

from .forms import ContactForm

from .hubspot import create_or_update_hubspot_contact

def contact_view(request​:disappointed_face:

message = ""

if request.method == "POST":

    form = ContactForm(request.POST)

    if form.is\_valid():

        email = form.cleaned\_data\["email"]

        firstname = form.cleaned\_data\["firstname"]

        api\_key = "pat-na1-51aea591-2569-4d97-b922-4ccbca04ed26" # Reemplaza esto con tu clave API de Hubspot

        success = create\_or\_update\_hubspot\_contact(api\_key, email, firstname)

        if success:

            message = f"Contact {email} created or updated successfully"

        else:

            message = f"An error occurred while creating or updating contact {email}"

else:

    form = ContactForm()

return render(request, "contact.html", {"form": form, "message": message})

hubspot.py

import requests

import json

def create_or_update_hubspot_contact(api_key, email, firstname​:disappointed_face:

url = f"https://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/{email}/?hapikey={api\_key}"

headers = {"Content-Type": "application/json"}

data = {

    "properties": \[

        {

            "property": "email",

            "value": email

        },

        {

            "property": "firstname",

            "value": firstname

        }

    ]

}

response = requests.post(url, headers=headers, data=json.dumps(data))

if response.status\_code == 200:

    return True

else:

    print(f"An error occurred: {response.text}")

    return False

When I run the code, I get the following error message: “An error occurred while creating or updating contact [email]”. I’ve tried generating new private API keys in my HubSpot account but I keep getting the same error.

Can anyone help me figure out what’s going wrong and how to fix it?

Thanks in advance for your help!

Hi, @kevinsito :waving_hand: Thanks for your question. I don’t have the answer, but I have sone questions that may help our community to better understand your issue.

  • You’re printing the response text when there’s an error. What’s the exact error message you’re getting?
  • The status code for a successful operation would be 200 or 204. You’re only checking for 200 which might be the issue. Can you try to print the status code to see if you’re getting 204?

Thank you for the additional information.

Best,

Jaycee