'How to Add Subscribe option in a Django Website

I am trying to add a subscribe to newsletter option on a django website. When a visitor enters a valid email address it will be stored in the database. The subscription form is part of the base.html template. All other templates of the website extend this template. I wish to implement this in a DRY way. This is how I am trying to do it :

forms.py :

from dataclasses import fields
from django import forms
from . models import Subscribers, MailMessage

class SubcribersForm(forms.ModelForm):
    class Meta: 
        model = Subscribers
        fields = ['email', ]

views.py :

def base(request):
    if request.method == 'POST':
        form = SubcribersForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = SubcribersForm()

    context = {'form': form}
    return render(request, 'base.html', context)

The template: base.html

        <form method = "POST" class="signup-form form-inline justify-content-center pt-3">
            {% csrf_token %}
            <div class="form-group">
                <label class="sr-only" for="semail">{{context}}</label>
                <input type="email" id="semail" name="semail1"  class="form-control mr-md-1 semail" placeholder="Enter email">
            </div>
            <button type="submit" class="btn btn-primary">Subscribe</button>
        </form>
            

models.py :

class Subscribers(models.Model):
    email = models.EmailField(null=True)
    date = models.DateTimeField(auto_now_add=True)

    def __str__self(self):
        return self.email

In the backend, I can see that the Subscribers table has been created. However, when I enter any email address from the home page and click subscribe button it does not store it in the database. What could be the issue here?



Solution 1:[1]

It could be that you have no action declared in your form. Assuming you have a url like this:

path('add-subscriber/', base, name='base'),

...your form would need a way to call it upon submit, like this:

        <form method = "POST" action="{% url 'base' %}" class="signup-form form-inline justify-content-center pt-3">
            {% csrf_token %}
            <div class="form-group">
                <label class="sr-only" for="semail">{{context}}</label>
                <input type="email" id="semail" name="semail1"  class="form-control mr-md-1 semail" placeholder="Enter email">
            </div>
            <button type="submit" class="btn btn-primary">Subscribe</button>
        </form>
            

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Milo Persic