[Fixed]-Django Forms Not adding objects to DB

1๐Ÿ‘

โœ…

[UPDATE 2]: Change your views.py to this:

def login(request):
    form = Login()
    if request.method == 'POST':
        form = Login(request.POST)
        if form.is_valid():
            username = form.cleaned_data['Username']
            password = form.cleaned_data['Password']
            TPerson = Person.objects.create(Username=username, Password=password)
    return render(request, 'photos/login.html', {'Login': form})

Then in your photos/login.html add these inside the <form> and check any errors:

<form action={% url 'login' %} method="POST">{% csrf_token %}
   <div style="padding-bottom: 10px;" >
       {% if Login.errors %}
           The errors are: <span>{{ Login.errors }}</span>
       {% endif %}
       <span>{{ Login }}</span>
   </div>
   <br/>
   <input type="submit" value="Submit" />

[UPDATE]: Change this <form action="/photos/memes.html" method="POST"> to this <form action="{% url 'login' %}" method="POST">.

You should better follow and complete the excellent Django tutorial. It will be good for you!

Several things happen in your code:

  1. Username=forms.cleaned_data['Username'] should be ....=form.cleaned_data['Username']. Not forms.

  2. You are getting the password from the request object, instead of the form. So, it should be like this: Password=form.cleaned_data['Password']

  3. There is no need to call TPerson.save(). The create() function will automatically save the object to database for you.

๐Ÿ‘คnik_m

0๐Ÿ‘

The form is presumably not valid. But in that case you create a new form instance, so you never show any validation errors. Remove that else clause and the template will show the errors.

๐Ÿ‘คDaniel Roseman

Leave a comment