DietkeSt / GraphicDesignShop

0 stars 1 forks source link

BUG: Newsletter would only show subscribe option #35

Open DietkeSt opened 2 months ago

DietkeSt commented 2 months ago

When user navigates to their account profile they should have the option to either sign up or unsubscribe for the newsletter. The user only sees subscribe option, no matter which status he is on.

{% if is_subscribed %}

{% csrf_token %}

Newsletter

You are currently signed up for our Newsletter.

Unsubscribe from Newsletter
{% else %}
<form action="{% url 'newsletter:subscribe_newsletter' %}" method="post">
    {% csrf_token %}
    <p class=" h3 pt-4 font-weight-bold">Newsletter</p>
    <p>Do you wish to subscribe to our Newsletter?</p>
    <a href="{% url 'newsletter:subscribe_newsletter' %}" class="fw-bold w-100 btn btn-primary">Subscribe to Newsletter</a>
</form>
{% endif %} 

def check_subscription_status(email): email_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest() api_key = settings.MAILCHIMP_API_KEY url = f"https://{settings.MAILCHIMP_SERVER_PREFIX}.api.mailchimp.com/3.0/lists/{settings.MAILCHIMP_LIST_ID}/members/{email_hash}" user_pass = base64.b64encode(f"anystring:{api_key}".encode()).decode('utf-8') headers = {"Authorization": f"Basic {user_pass}"}

response = requests.get(url, headers=headers)
if response.status_code == 200:
    data = response.json()
    return data['status'] in ['subscribed', 'pending']
return False
DietkeSt commented 2 months ago

This was fixed by adding the connection of the check to the edit details view for their profile:

Check newsletter subscription status

is_subscribed = check_subscription_status(request.user.email)

return render(request, 'account/user/edit_details.html', { 'user_form': user_form, 'is_subscribed': is_subscribed })

Now the correct option is displayed for the user.