Search code examples
djangodjango-modelsdjango-viewsdjango-admindjango-database

I cant view my form inputs in the django database


I am a learner in django. i have created my first form, but when i input data i dont see it in my database but see in in my shell. I have rechecked my code but it seem fine, yet still it wont save in my code in the database. Please help me out here.Thanks.

Model:

from django.db import models

class Login(models.Model):
    first_name = models.CharField(max_length=200)
    second_name = models.CharField(max_length=200)
    email = models.EmailField()
    password = models.CharField(max_length=200)

View:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Login
from .forms import login_form

def homeview(request):
    return HttpResponse("<h1>Hello There</h1>")

def login_view(request):
    form = login_form(request.POST or None)

    if form.is_valid:
        form.save
    context = {
        "form":form
    }   

    return render(request, "login.html", context)

Template:

{% block content %}

<form action="" method="GET">{% csrf_token %}

{{form.as_p}}
<input type="submit" value="Login"/> 
</form>

{% endblock %}

Form:

from django import forms
from .models import Login

class login_form(forms.ModelForm):
    class Meta:
        model = Login
        fields = [
            "first_name",
            "second_name",
            "email",
            "password"
        ]

Solution

  • Following lines are incorrect:

        if form.is_valid:
            form.save
    

    Currently the if will always return True because .is_valid returns the bound method.

    You need to call is_valid -> form.is_valid()

    Same for form.save. You would only return the bound method save, but you don't call it.

    These lines would look like this:

        if form.is_valid():
            form.save()
    

    Furthermore: In your template the used method for your form is GET but you are accessing request.POST. You need to change either one of them to the other method, e.g. method="POST".