Marcus
Marcus

Reputation: 161

Django form not rendering widget

I can't figure out, why the django form widget is not rendered in the browser.

This is my form:

from django import forms
from .models import RealEstateTax

class CreateRealEstateForm(forms.ModelForm):
    class Meta: 
        model = RealEstateTax
        fields = ['invoice_number',]
        widget = {
            'invoice_number': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here'}),
        }

Just for testing purposes, I reattributed the field as a Textarea and gave it a class where the text should appear red.

This is the template:

{% extends 'main.html' %}
{% load static %}

{% block title %} Create Realestate Tax {% endblock %}

{% block content %}

<style>
    .form-control {
        color: red;
    }
</style>


<form method="post">
    <div class="form-group">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-info">Send</button>
    </div>
</form>


{% endblock %}

When I inspect the element in the browser, there is no class, it is not a Textarea and the text is not red:

Inspected element in the browser

This is what I specified in the view:

from realestate.models import RealEstate
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.db.models import Sum
from realestate.models import RealEstate
from .forms import CreateRealEstateForm

def create_real_tax(request):
    form = CreateRealEstateForm
    if request.method == 'POST':
        form = CreateRealEstateForm(request.POST)
        if form.is_valid():
            form.save()

    print(form.base_fields)
    context = {'form':form}
    return render(request, 'billing/create_real_tax.html', context)

I hope you can help me figure this out.

Many thanks in advance!

Upvotes: 1

Views: 1420

Answers (2)

Mahmudul Alam
Mahmudul Alam

Reputation: 153

Can you please try to change the widget to widgets like this:

widgets = {
            'invoice_number': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here'}),
        }

Upvotes: 1

Mridul
Mridul

Reputation: 143

Try replacing form = CreateRealEstateForm with form = CreateRealEstateForm(). You are currently only rendering the form if the request is a POST request and simply referencing the class when the request is GET.

Additionally, try changing the form to:

class CreateRealEstateForm(forms.ModelForm):
    class Meta: 
        model = RealEstateTax
        fields = ['invoice_number',]
        widget = {
            'invoice_number': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Text goes here'}),
        }

Upvotes: 1

Related Questions