Search code examples
djangodjango-modelsdjango-formsdjango-viewsnewsletter

Need help to solve newsletter form issues in base template


Here is what i have in base.html (inside the footer, so this newsletter form will be in every page)

<form action="" method="POST">
                            {% csrf_token %}
                            <div class="form-group">
                                <div class="input-group mb-3">
                                    <input type="text" class="form-control" placeholder='Enter email address' onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'">
                                    <div class="input-group-append">
                                        <button class="btn" type="submit"><span class="lnr lnr-arrow-right"></span></button>
                                    </div>
                                </div>
                            </div>
                        </form>

Here is the model (subscribe/models.py)

class Subscriber(models.Model):
    email = models.EmailField()
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.email

what i have in views.py

def subscribe_form(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        new_email = Subscriber()
        new_email.email = email
        new_email.save()
    return redirect('home-page')

here is urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.PostListView.as_view(), name='home-page'),
    path('subscribe/', views.subscribe_form, name='subscriber'),
    path('archive/', views.archive, name='archive-page'),
    path('category/', views.category, name='category-page'),
    path('contact/', views.contact, name='contact-page')
]

after submitting the submit button i'm getting this error in shell

Method Not Allowed (POST): /
Method Not Allowed: /
[18/Jan/2020 04:13:11] "POST / HTTP/1.1" 405 0

so, i'm a beginner, im trying to build a blog, but i didn't find any useful solution that can solve this issue. maybe i'm going totally wrong, but anyway if someone can help me to make this working. Thank you all.


Solution

  • In your index URL, you are not allowed to post.So change it to subscribe/

    <form action="{% url 'subscriber' %}" method="POST>