Working with forms

74 views
Skip to first unread message

Ifeanyi Chielo

unread,
Apr 4, 2020, 12:34:05 AM4/4/20
to Django users
Hello,I developed a form with a single field, but this form displays only the submit button at the browser as shown in the image below. Please how can I correct this and also  save the field to the MySQL table.  My code is also shown below

django form.png


View.py

from django.http import HttpResponseRedirect

from django.shortcuts import render

from .models import Namerec

from .forms import NameForm

from django.views.generic import TemplateView

 

def HomePageView (request, *args, **kwargs):

     return render(request,"home.html", {})

def Namev_view (request):

        if request.method == 'POST':

            form = NameForm (request.POST)

            if NameForm.is_valid():

                NameForm.save()

            context = {

                'form': form

                }

        return render(request, 'namev.html', {})

form.py

from .models import Namerec

from django import forms

class NameForm(forms.Form):

    your_name = forms.CharField(label='Your name'max_length=100)

template (namev.htlm)

<form action="/namev/" method="Post">

    {% csrf_token %}    

    {{ form  }}

    <input type="submit" value="Submit">

</form>

 


 

Model.py

from django.db import models

class Namerec(models.Model):

    your_name = models.CharField(max_length=30)

   


victor awakan

unread,
Apr 4, 2020, 12:41:19 AM4/4/20
to django...@googlegroups.com
In the form template tag, shouldn’t it be {{ form.as_p}} tag?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f50577dd-d5c0-4478-8993-7bab533f24f9%40googlegroups.com.

Ifeanyi Chielo

unread,
Apr 4, 2020, 12:50:07 AM4/4/20
to Django users
Thanks Victor, 
I did it and it does not make any cnange

On Saturday, April 4, 2020 at 1:41:19 AM UTC+1, victor awakan wrote:
In the form template tag, shouldn’t it be {{ form.as_p}} tag?
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

Bruckner de Villiers

unread,
Apr 4, 2020, 5:35:25 AM4/4/20
to django...@googlegroups.com

Please share code for home.html & urls.py.  Also have you included the app name in the settings.py?

Thanks,

 

Bruckner de Villiers

083 625 1086

 

From: <django...@googlegroups.com> on behalf of Ifeanyi Chielo <ifeanyi...@unn.edu.ng>
Reply to: <django...@googlegroups.com>
Date: Saturday, 04 April 2020 at 02:51
To: Django users <django...@googlegroups.com>
Subject: Re: Working with forms

 

Thanks Victor, 

I did it and it does not make any cnange


On Saturday, April 4, 2020 at 1:41:19 AM UTC+1, victor awakan wrote:

In the form template tag, shouldn’t it be {{ form.as_p}} tag?

On Sat 4. Apr 2020 at 3.35, Ifeanyi Chielo <ifeany...@unn.edu.ng> wrote:

Hello,I developed a form with a single field, but this form displays only the submit button at the browser as shown in the image below. Please how can I correct this and also  save the field to the MySQL table.  My code is also shown below

To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9825aec7-7e87-4d4a-80f9-634cb9e4dd59%40googlegroups.com.

Ifeanyi Chielo

unread,
Apr 4, 2020, 8:43:55 AM4/4/20
to django...@googlegroups.com
Hello,
Here are the codes: 

View

from django.http import HttpResponseRedirect

from django.shortcuts import render

from .models import Namerec

from .forms import NameForm

from django.views.generic import TemplateView

 

def HomePageView (request, *args, **kwargs):

     return render(request,"home.html", {})

 

project url

from django.contrib import admin

from django.urls import path, include

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('pages.urls')),

]

 

 

App url

urlpatterns = [

    path('', HomePageView, name = 'home'),

    path('namev/', Namev_view),

    #path('', HomePageView),

    #path('namev/', Nameview_view),

 

]

 Note, I have not written any code at home.html template and it is rendering well


Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN


Ifeanyi Chielo

unread,
Apr 4, 2020, 8:46:49 AM4/4/20
to django...@googlegroups.com
Yes the app name is already included in the settings.py

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

On Sat, Apr 4, 2020 at 6:35 AM Bruckner de Villiers <bruckner....@gmail.com> wrote:

Luqman Shofuleji

unread,
Apr 4, 2020, 9:09:39 AM4/4/20
to django...@googlegroups.com
In def Namev_view under views.py, include form in the return parameter and see if that resolves the issue

return render(request, 'namev.html', {'form':form})



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Ifeanyi Chielo

unread,
Apr 4, 2020, 11:33:26 AM4/4/20
to django...@googlegroups.com
Thanks a lot, 
I did as you said and I encountered the error message below:

UnboundLocalError at /namev/

local variable 'form' referenced before assignment
Request Method: GET
Request URL: http://localhost:8000/namev/
Django Version: 2.1.5
Exception Type: UnboundLocalError
Exception Value:
local variable 'form' referenced before assignment
Exception Location: C:\Users\IFEANYI CHIELO\divinecrownapp\pages\views.py in Namev_view, line 42
Python Executable: C:\Users\IFEANYI CHIELO\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.2
Python Path:
['C:\\Users\\IFEANYI CHIELO\\divinecrownapp',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
Server time: Sat, 4 Apr 2020 11:27:07 +0000

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

KONE GOMPOU LOUA ALASSANE

unread,
Apr 4, 2020, 11:35:30 AM4/4/20
to django...@googlegroups.com
Send screen short

--
La meilleure façon de prédire l’avenir est de le créer. 


KONE GOMPOU LOUA ALASSANE

unread,
Apr 4, 2020, 11:36:34 AM4/4/20
to django...@googlegroups.com
But i thing that this problem is due to bad indentation 

Ifeanyi Chielo

unread,
Apr 4, 2020, 12:08:41 PM4/4/20
to django...@googlegroups.com
Screen shorts of codes available above

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

Luqman Shofuleji

unread,
Apr 4, 2020, 2:22:06 PM4/4/20
to django...@googlegroups.com
Okay, now the new error is that is not seeing that 'form' for the get request,
you need to also add  form = NameForm () before the if statement "if request.method == 'POST' " to handle the page get request.



Ifeanyi Chielo

unread,
Apr 4, 2020, 3:34:36 PM4/4/20
to django...@googlegroups.com
Thanks a lot, I believe I am close to the result. I did exactly what you instructed and another error appeared thus:

ValueError at /namev/

The view pages.views.Namev_view didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://localhost:8000/namev/
Django Version: 2.1.5
Exception Type: ValueError
Exception Value:
The view pages.views.Namev_view didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\IFEANYI CHIELO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py in _get_response, line 137
Python Executable: C:\Users\IFEANYI CHIELO\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.2
Python Path:
['C:\\Users\\IFEANYI CHIELO\\divinecrownapp',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
Server time: Sat, 4 Apr 2020 15:27:13 +0000
Meanwhile the current code for the view is shown below:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .models import Namerec
from .forms import NameForm
from django.views.generic import TemplateView

def HomePageView (request, *args, **kwargs):
     return render(request,"home.html", {})
def Namev_view (request):
    form = NameForm ()
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
            form = NameForm (request.POST)
        # check whether it's valid:
            if NameForm.is_valid():
                NameForm.save()
            context = {
                'form': form
                }
            return render(request, 'namev.html', {'form':form})

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

Luqman Shofuleji

unread,
Apr 4, 2020, 4:33:04 PM4/4/20
to django...@googlegroups.com
Your current error is because you have modify your code and placed the "return render(request .... " line under "if request.method == "POST"  .
This wasn't the case in the first view.py code you posted.

That line of code must not be under the if statement but should be at same level of indentation with it.
By putting it under the if statement, it means that line is only applicable to the POST request which resulted in the error you are having.

The line I'm referring to is this:
return render(request, 'namev.html', {'form':form})


Ifeanyi Chielo

unread,
Apr 4, 2020, 5:13:04 PM4/4/20
to django...@googlegroups.com
Thanks for the correction. The moment I made the correction, the error message but the form was not rendered. See:
 attachments below
def Namev_view (request):
    form = NameForm()
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
            form = NameForm (request.POST)
        # check whether it's valid:
            if NameForm.is_valid():
                NameForm.save()
            context = {
                'form': form
                }
    return render(request, 'namev.html', {'form':form})

image.png

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

KONE GOMPOU LOUA ALASSANE

unread,
Apr 4, 2020, 5:50:29 PM4/4/20
to django...@googlegroups.com
Replace in the return... {´form’:form} by context to get something like that return render (request, ‘namev.html’, context)

Ifeanyi Chielo

unread,
Apr 5, 2020, 7:17:26 AM4/5/20
to django...@googlegroups.com
Hello,
I replaced with 'context' as Kone said and I had an unboundLocalError message below

"UnboundLocalError at /namev/

local variable 'context' referenced before assignment"
I then tied to correct the error by adding a line of code: context = {'form': form}
then only the submit button was rendered again at the browser, without the complete form  as shown below
image.png
def Namev_view (request):
    form = NameForm()
    context = {'form':form}
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
            form = NameForm (request.POST)
        # check whether it's valid:
            if NameForm.is_valid():
                NameForm.save()
            context = {
                'form': form
                }
    return render(request, 'namev.html', context)
    # return render(request, 'namev.html', {'form':form})
Dr. Chielo C. Ifeanyi = 
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

Ifeanyi Chielo

unread,
Apr 5, 2020, 12:55:02 PM4/5/20
to django...@googlegroups.com
Thanks guys, 
The complete forms is now rendering well. I took my time to make some necessary corrections as shown below: The next challenge is that it is not saving in the mysql database, so I still need your assistance in this area.
def HomePageView (request, *args, **kwargs):
     return render(request,"home.html", {})
def Namev_view (request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/namev/')
    else:
        form = NameForm()
    return render(request, 'namev.html', {'form': form})
Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

KONE GOMPOU LOUA ALASSANE

unread,
Apr 5, 2020, 1:28:30 PM4/5/20
to django...@googlegroups.com
form=NameForm(request.POST):
//Now use form instead of NameForm
if form.is_valid():
//And make that you have the right indentation
...

Alejandro Avendano

unread,
Apr 5, 2020, 1:45:20 PM4/5/20
to Django users
Hi in the first version, you had:
NameForm.is_valid():
NameForm.save()

But on the second, version the "NameForm.save()" is missing. This is the line of code that save into you database. Maybe, should try putting it back...

jill patel

unread,
Apr 5, 2020, 1:45:31 PM4/5/20
to django...@googlegroups.com
You forgot to put form.save after it satisfies the if condition 

Ifeanyi Chielo

unread,
Apr 5, 2020, 2:04:06 PM4/5/20
to django...@googlegroups.com
I added the NameForm.Save() attribute and I had an AttributeError message thus:

AttributeError at /namev/

type object 'NameForm' has no attribute 'save'
Request Method: POST
Request URL: http://localhost:8000/namev/
Django Version: 2.1.5
Exception Type: AttributeError
Exception Value:
type object 'NameForm' has no attribute 'save'
Exception Location: C:\Users\IFEANYI CHIELO\divinecrownapp\pages\views.py in Namev_view, line 16
Python Executable: C:\Users\IFEANYI CHIELO\AppData\Local\Programs\Python\Python37\python.exe
Python Version: 3.7.2
Python Path:
['C:\\Users\\IFEANYI CHIELO\\divinecrownapp',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
Server time: Sun, 5 Apr 2020 13:59:01 +0000

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

KONE GOMPOU LOUA ALASSANE

unread,
Apr 5, 2020, 2:07:12 PM4/5/20
to django...@googlegroups.com
Use form. save() because you asigned NameForm to form like

Ifeanyi Chielo

unread,
Apr 5, 2020, 2:22:38 PM4/5/20
to django...@googlegroups.com
I tried using the form. save() but it gave the same error message as with NameForm.save()

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

Joshua Kayode

unread,
Apr 5, 2020, 5:35:53 PM4/5/20
to django...@googlegroups.com
Ask questions here for immediate and detailed response djangoafrica.com and join the WhatsApp group, a community of professional django developers 

Group1 

Group2: 

Django africa is a community of django developers....

Excellence for all....

Ifeanyi Chielo

unread,
Apr 5, 2020, 6:08:19 PM4/5/20
to django...@googlegroups.com
Thanks

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

Ifeanyi Chielo

unread,
Apr 5, 2020, 9:32:32 PM4/5/20
to django...@googlegroups.com
Please I am still left with the AttributeError, The form is now publishing fully and very well but it cannot save to the MySQL table. below is the error details and the recent code of view.py

AttributeError at /namev/

'NameForm' object has no attribute 'save'
Request Method:POST
Request URL:http://localhost:8000/namev/
Django Version:2.1.5
Exception Type:AttributeError
Exception Value:
'NameForm' object has no attribute 'save'
Exception Location:C:\Users\IFEANYI CHIELO\divinecrownapp\pages\views.py in Namev_view, line 17
Python Executable:C:\Users\IFEANYI CHIELO\AppData\Local\Programs\Python\Python37\python.exe
Python Version:3.7.2
Python Path:
['C:\\Users\\IFEANYI CHIELO\\divinecrownapp',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib',
 'C:\\Users\\IFEANYI CHIELO\\AppData\\Local\\Programs\\Python\\Python37',
 'C:\\Users\\IFEANYI '
 'CHIELO\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
Server time:Sun, 5 Apr 2020 19:46:34 +0000
CODE FOR VIEW.PY
ef Namev_view (request):
    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/namev/')
    else:
        form = NameForm()
    return render(request, 'namev.html', {'form': form})

Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN
On Sat, Apr 4, 2020 at 3:21 PM Luqman Shofuleji <luqma...@gmail.com> wrote:

Alejandro Avendano

unread,
Apr 5, 2020, 9:53:33 PM4/5/20
to Django users
Hi Chielo, 

Actually, save() is a method of the class forms.ModelForm. But your form class is extending from forms.Form instead.
Please, modify your form.py as follow:


class NameForm (forms.ModelForm)

    class Meta:

        model = Namerec

        fields = ['your_name’,] 

To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

Maro Okegbero Samuel

unread,
Apr 5, 2020, 11:04:55 PM4/5/20
to Django users
Port your code back to the initial state it was when you asked the question and on the template change
 {{form}} to {{form.as_p}}


Ifeanyi Chielo

unread,
Apr 6, 2020, 5:26:28 AM4/6/20
to django...@googlegroups.com
Thanks to you all, I finally resolved the matter. I discovered it was just of a mix up of ModelForm and ordinary Django forms, though I enjoyed the teething challenges as a new django user 
Dr. Chielo C. Ifeanyi
Chief Programmer,
Head Webometrics Section
ICT Unit, UNN

On Mon, Apr 6, 2020 at 12:04 AM Maro Okegbero Samuel <marook...@gmail.com> wrote:
Port your code back to the initial state it was when you asked the question and on the template change
 {{form}} to {{form.as_p}}


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/063525f8-c177-47d6-b849-52240522ae4f%40googlegroups.com.

waqar khan

unread,
Apr 6, 2020, 1:35:17 PM4/6/20
to django...@googlegroups.com
hey
I am waqar,
 i have created user form but not working
please solve my problems 

admin:
username:-admin
password:-admin

user:
username:-waqar
password:-Test@123



userproject.zip
Reply all
Reply to author
Forward
0 new messages