my generic view inherited from CreateView in django does not show model fields to fill out when I run my django project

27 Views Asked by At

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'?

1

There are 1 best solutions below

0
Rajat On

You had put an empty html file. You can do this -

<form method="POST" enctype="multipart/form-data">
 
    <!-- Security token -->
    {% csrf_token %}
 
    <!-- Using the formset -->
    {{ form.as_p }}
     
    <input type="submit" value="Submit">
</form>

You can also put custom html file name -

class EmployeeCreate(CreateView):
    model = Employee
    fields = '__all__'
    #coustom html file name
    template_name = 'sampleapp/employee_form.html'

Also check that 'DIRS': ['templates'] in settings.py file.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
         .
         .
         .