Gaius G D'cruz
Gaius G D'cruz

Reputation: 63

Django form not rendering in the html page

I am learning Django and have created the form using ModelForms. First I wrote the views.py as function but once I tried to make it class the form is not rendering while rest of the tags are working. This is my views.py in function method

def company(request):
    company = Company.objects.all()
    cform = CompanyForm()
    form = CompanyForm(request.POST or None)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/company')
    return render(request,'company/company.html',{
        'company': company,
        'cform':cform
    })

This is class based views.py

class CompanyView(generic.TemplateView):
    model = 'Company'
    template_name = 'company/company.html'

I have updated the urls.py like this

urlpatterns = [
    path('',views.IndexView.as_view(), name='index'),
    path('form/',views.CompanyView.as_view(),name='company'),
]

Finally this is my html template

<h1>{{ company.company_name }}</h1>
<ul>
    {% for company in company.choice_set.all %}
    <li>{{ company.company_name }}</li>
    {% endfor %}
</ul>

<form method="post">
    {% csrf_token %}
    <fieldset>
        <legend>
            <h2> Company Form </h2>
        </legend>

        {{ cform.as_p }}

    </fieldset>
    <input type="submit" value="Submit" />
</form>

and forms.py

from .models import Company

# create a ModelForm
class CompanyForm(forms.ModelForm):
    
    class Meta:
        model = Company
        fields = ('company_name','location','email_id')

When class CompanyView(generic.DetailView): is given I get an exception of Exception Type: AttributeError at /company/form/ Exception Value: 'str' object has no attribute '_default_manager'. When its updated to class CompanyView(generic.FormView): the error exception is 'NoneType' object is not callable

class CompanyView(generic.TemplateView): renders everything except the {{ cform.as_p }}

I tried many changes to the template and all but I am not able to find the error here.

Upvotes: 0

Views: 350

Answers (1)

Andries D. Niemandt
Andries D. Niemandt

Reputation: 146

If you are using class based views, you do not need the function definition as you have it above, be sure to remove it. Refer to the docs here

Try this class based definition and template:

class CompanyView(generic.FormView):
    template_name = 'company/company.html'
    form_class = CompanyForm
    success_url = '/redirect-to-somewhere/'

And then in your HTML, refer to only {{ form.as_p }}:

<form method="post">
    {% csrf_token %}
    <fieldset>
        <legend>
            <h2> Company Form </h2>
        </legend>

        {{ form.as_p }}

    </fieldset>
    <input type="submit" value="Submit" />
</form>

Upvotes: 1

Related Questions