Home > Net >  NOT NULL constraint failed: posts_subscribe.firstname
NOT NULL constraint failed: posts_subscribe.firstname

Time:06-20

I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button, I keep on getting the following error:

NOT NULL constraint failed: posts_subscribe.firstname

Here is my views.py

def subscribe(request):
    if request.method == 'POST':
        firstname=request.POST.get('firstname')
        secondname=request.POST.get('secondname')
        email=request.POST.get('email')
        phonenumber=request.POST.get('phonenumber')
        en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
        en.save()

        return redirect('/')
        
    return render(request, 'subscribe.html')

My models.py

class Subscribe(models.Model):
    firstname = models.CharField(max_length=30, blank = True)
    secondname = models.CharField(max_length=30, blank = True)
    email = models.CharField(max_length=30)
    phonenumber = models.IntegerField()

Here is my template

{% extends 'index.html' %}
{% block subscribe %}
<div >
    <h1 > Subscribe</h1>
    <form method="POST" enctype="multipart/form-data" action="subscribe">
        {% csrf_token %}
        <div >
            <label for="firstname" >First Name</label>
            <input type="text"  id="firstname" placeholder="firstname">
        </div>
        <div >
            <label for="secondname" >Second Name (Optional)</label>
            <input type="text"  id="secondname" placeholder="secondname">
        </div>
        <div >
            <label for="email" >Email</label>
            <input type="email"  id="email" placeholder="[email protected]">
        </div>
        <div >
            <label for="phonenumber" >Phonenumber</label>
            <input type="number"  id="phonenumber" placeholder="0712345678">
        </div>
        <div >
            <button type="submit" > Subscribe</button>
        </div>     
    </form>
</div>
{% endblock %}

And my url patterns


urlpatterns= [
    path('', views.index, name='index'),
     
    path('subscribe', views.subscribe, name ='subscribe'),
    path('allposts', views.allposts, name='allposts'),
    path('political', views.political, name='political'),
    path('religion', views.religion, name='religion'),
    path('trending', views.trending, name='treniding'),
   
    path('<str:pk>', views.post, name='post'),
 
   
]

Any help would be much appreciated

CodePudding user response:

You should add a name="…" attribute [mdn] to the <input> elements, so:

<input type="text" name="firstname"  id="firstname" placeholder="firstname">
…
<input type="text" name="secondname"  id="secondname" placeholder="secondname">
…
<input type="email" name="email"  id="email" placeholder="[email protected]">
…
<input type="number" name="phonenumber"  id="phonenumber" placeholder="0712345678">
  • Related