I create an app in django named 'sampleapp' then in models.py I define my model as follows:
from django.db import models
from django.urls import reverse
class Employee(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
mobile = models.CharField(max_length=10)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
and also in forms.py:
from .models import Employee
from django import forms
class EmployeeForm(forms.ModelForm):
class Meta:
# To specify the model to be used to create form
model = Employee
# It includes all the fields of model
fields = '__all__'
then in views.py:
from django.shortcuts import render
from .models import Employee
from .forms import EmployeeForm
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
class EmployeeCreate(CreateView):
model = Employee
fields = '__all__'
and in urls.py file:
from django.urls import path
from .views import EmployeeCreate
urlpatterns = [
path('', EmployeeCreate.as_view(), name='EmployeeCreate')
]
and also I put employee_form.html (an empty html file) in 'myproject/template/sampleapp/employee_form.html'. But when I run my project and go to url "http://127.0.0.1:8000/" I receive an empty html file, a page without any field to fill out (like first_name field last_name field and so on). How can I create an Employee object using django generic view 'CreateView'?
You had put an empty html file. You can do this -
You can also put custom html file name -
Also check that 'DIRS': ['templates'] in settings.py file.