I'm trying to display a basic form in django but does not render the form once I run the server, I would appreciate if you could help me with these, here my code.
models.py
STATUS_OPTIONS =(
('OP', 'OPEN'),
('CL', 'CLOSED')
)
class Employee(models.Model):
id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=200)
status = models.CharField(max_length=50, choices=STATUS_OPTIONS)
password = models.CharField(max_length=100)
def __str__(self):
return self.first_name
forms.py
from django import forms
from .models import Employee
class EmployeeForm(forms.Form):
class Meta:
model = Employee
fields = "__all__"
urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.create_employee),
]
views.py
from .forms import EmployeeForm
# Create your views here.
def create_employee(request):
form = EmployeeForm()
return render(request, 'employee/create_employee.html', {'form':form})
create_employee.html
<h1>Formu</h1>
<form action="" method='POST'>
{{form.as_p}}
<input type="submit">
</form>
When I run the program the only thing rendered is the tag, any idea?
In order to create forms out of models you need to use ModelForm
not Form
. Otherwise you end up with a regular form without any field.
from django.forms import ModelForm
from .models import Employee
class EmployeeForm(ModelForm):
#...
More about ModelForm
here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.