skip to Main Content

I would like my newsletter signup to only allow diffrent emails to signup and not allow the same email to sign up multiple times with a message email is allready in use. I cant seem to figure it out any help would be appreciated. The code is below i added the code i thought was usefull if u need more to figure it out i can post it, its a small app in a bigger project just for the email newsletter signup.

newsletter template

{% load static %}
{% block page_header %}
    <div class="container header-container">
        <div class="row">
            <div class="col"></div>
        </div>
    </div>
{% endblock %}
<div id="delivery-banner" class="row text-center">
    <div class="col bg-success text-white">
        <h4 class="logo-font my-1">Sign up to Newsletter and get 5% discount</h4>
    </div>

<div class="content-wrapper text-center bg-warning container-fluid" id="newsletter-wrapper">

    <form v-on:submit.prevent="onSubmit">
        <div class="card text-black bg-warning  mb-3">
        <div class="card-footer">
            <div class="alert alert-success" role="alert" v-if="showSuccess">
                You are Subscribed to our Newsletter!
            </div>
            <h2>Subscribe to our newsletter</h2>
            <div class="form-group">
                <input type="email" class="" v-model="email" name="email" class="input" placeholder="e-mail address" required>
            </div>
            <div class="form-group">
                <button class="btn btn-success ">Submit</button>
            </div>
        </div>
        <div class="social">
                  <a target="_blank" rel="noopener noreferrer" href="https://facebook.com/" class="btn btn-social-icon btn btn-primary btn-outline-facebook "><i class="fa fa-facebook"></i></a>
                  <a target="_blank" rel="noopener noreferrer" href="https://youtube.com/" class="btn btn-social-icon btn btn-danger btn-outline-youtube"><i class="fa fa-youtube"></i></a>
                  <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/" class="btn btn-social-icon btn btn-info btn-outline-twitter"><i class="fa fa-twitter"></i></a>
                  <a target="_blank" rel="noopener noreferrer" href="https://linkedin.com/" class="btn btn-social-icon btn btn-dark btn-outline-linkedin"><i class="fa fa-linkedin"></i></a>
                </div>
    </form>

</div>
</div>

<script>
    var newsletterapp = new Vue({
        el: '#newsletter-wrapper',
        data () {
            return {
                email: '',
                showSuccess: false
            }
        },
        methods: {
            onSubmit() {
                console.log('onSubmit')

                fetch('/api/add_subscriber/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}'
                        },
                        body: JSON.stringify({'email': this.email})
                    })
                    .then((response) => {
                        return response.json()
                    })
                    .then((data) => {
                        console.log(data)

                        this.showSuccess = true
                        this.email = ''
                    })
                    .catch(function(error) {
                        this.showSuccess = false
                        console.log('Error:', error);
                    });
            }
        }
    })
</script>

admin.py

from django.contrib import admin

from .models import Subscriber

admin.site.register(Subscriber)

models.py

from django.db import models

class Subscriber(models.Model):
    email = models.EmailField(max_length=255)
    date_added = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return '%s' % self.email

views.py is empty

3

Answers


  1. def clean_email(self):
        if User.objects.filter(email=self.cleaned_data['email']).exists():
            raise forms.ValidationError("the given email is already registered")
        return self.cleaned_data['email']
    

    add the code above in your models.py

    Login or Signup to reply.
  2. For whatever field you want it to be duplicated you can use unique=True in the definition of the field. Your models has to define something like the following.

    from django.db import models
    
    class Subscriber(models.Model):
        email = models.EmailField(max_length=255, unique=True)
        date_added = models.DateTimeField(auto_now_add=True)
    
    
        def __str__(self):
            return '%s' % self.email
    
    Login or Signup to reply.
  3. Another approach is to use get_or_create like if the subscriber already exists return already exists msg if not create one. Your api_add_subscriber function will be

    def api_add_subscriber(request):
        data = json.loads(request.body)
        email = data['email']
        subscriber, created = Subscriber.objects.get_or_create(email=email)
        if created:
            success = True
            msg = "You subscribed!"
        else:
            success = False
            msg = "This email has already subscribed!"
        return JsonResponse({'success': success, 'msg': msg})
    

    And you handle accordingly in the frontend;

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