ModelForm in Django not displaying CSS class when extending another ModelForm

I'm having trouble assigning a CSS class to a form field, even after following the guidance in this Stack Overflow post: CSS styling in Django forms

Specifically, I am facing issues when working with a ModelForm that extends another ModelForm. In the code snippet below, the fields "title" and "base_title" are supposed to have classes "title" and "base_title" respectively. However, upon checking the HTML output, neither of them actually receives any class. Any suggestions or advice on how to fix this would be greatly appreciated. Thank you.

Below is the relevant code:

models.py:

from django.db import models

class BaseModel(models.Model):
    base_title = models.CharField(max_length=50, blank=True)

class MyModel(BaseModel):
    title = models.CharField(max_length=50, blank=True)

forms.py:

from django.forms import ModelForm, TextInput
from testproj.models import MyModel

class BaseModelForm(ModelForm):

    class Meta:
        model = MyModel
    fields = ("base_title",)
    widgets = {
        "base_title" : TextInput(attrs={"class" : "base_title"}),
    }

class MyModelForm(BaseModelForm):

    class Meta(BaseModelForm.Meta):
        model = MyModel
        fields = BaseModelForm.Meta.fields + ("title",)
        widgets = BaseModelForm.Meta.widgets.update({
            "title" : TextInput(attrs={"class" : "title"}),
        })

views.py:

from django.shortcuts import render_to_response
from django.template import RequestContext

from testproj.forms import MyModelForm

def index(request):

    form = MyModelForm()

    return render_to_response(
        "testproj/index.html",
        {
            "form": form,
        }, 
            context_instance=RequestContext(request)
    )

Answer №1

After some investigation, it was discovered that the issue stemmed from improperly updating the widget dictionary. To resolve this, the MyModelForm class should be structured as shown below:

class MyModelForm(BaseModelForm):
    class Meta(BaseModelForm.Meta):
        model = MyModel
        fields = BaseModelForm.Meta.fields + ("title",)
        widgets = BaseModelForm.Meta.widgets
        widgets.update({
        "title" : TextInput(attrs={"class" : "title"}),
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate right side padding into a horizontal scroll?

I'm attempting to include padding on the right side of a horizontal scroll so that the last item in the scroll appears in the center of the screen. Here's what I have tried so far. While the left padding works perfectly, I'm puzzled as to w ...

Best practices for ensuring text remains in the correct position on all screen sizes when overlaying a large image

In the introductory page, I have a large image that spans more than 4000px in width to accommodate different resolutions. The image is set with the following CSS: #source-image { width: 100%; position: absolute; top: 0; left: 0; } On top ...

Error message from Django: "Page not found" due to missing year specification in detailed view

I am currently working on developing an app using the knowledge shared by Kenneth Love in his course "Getting Started with Django" at PyCon 2014. This crash course is a great resource for learning about Django and you can watch it here. However, I have e ...

What is the optimal HTML tag for showcasing chat text conversations?

To create a text window with fixed width and length that automatically wraps long texts without a horizontal scroll bar but with a vertical one, you can use HTML and CSS. The preview window on SO's ask question page is a good example of this. It is si ...

Ensuring the width of a div matches the adjacent containers

I need assistance in creating a form that adjusts its width based on the form fields. The form contains both explanatory text and input fields, each enclosed in a div with inline-block set. The outer div (also using inline-block) should not expand beyond ...

Efficient method for automatically filling all tiers within a tree structure within a Django layout

I have a tree structure with multiple levels. Bucky from thenewboston emphasized the importance of not violating the first rule of coding - Never repeat the code. Despite this advice, I find myself struggling to avoid repetition in my tree implementation. ...

Personalized hover effect using CSS on Caldera Forms

Struggling to customize the CSS style of my Caldera forms on a WordPress site. My goal is to add a hover effect to the radio checklist fields. Currently, I've only managed to style the bullets and need help adding a hover effect to the fields themselv ...

Implementing dynamic class changes with *ngIf within a child component

Apologies if this question has been addressed before, I found two similar answers here: Question related | Close Solution An Angular Material Sidenav component contains three components. The parent component (highlighted in red) includes tab-like but ...

Prevent the cascading of CSS styles on child list items

When constructing my menu, I have organized it using the following HTML structure: <div id=”navigation”> <ul> <li class=”level1”>Top Level Menu item <div class=”sublevel”> <ul> ...

I would like to hide the Carousel arrows and indicators if there is just one item

Is there a way to hide the next and previous arrows on images if there is only one image available? https://i.sstatic.net/vuAIc.png <Col md={6}> <Carousel> {product.image ? <Carousel.Item> <img ...

Having difficulty submitting a form with ajax, while accomplishing the same task effortlessly without ajax

I have been experimenting with submitting a form using ajax to the same .php file. When I submit the form without ajax directly (form action), the database gets updated. However, when I try the same process with ajax, there is no change in the database. H ...

IE11 displaying empty placeholders instead of PrimeNG icons after deployment on server

Currently, I am in the midst of an Angular project that heavily relies on PrimeNg for various components. While everything runs smoothly when testing the project locally across all browsers (including IE11 and Chrome), a hiccup arises once the project is ...

The sole focus is on the animation within the div

Is it possible to have a circle animation within a button without overlapping it? Check out my code on this fiddle. $(document).ready(function(){ $('button').on("mouseup",function(){ $('#mousemark').removeClass("c ...

Adding a watermark or overlay to an image using JavaScript and PHP

I am working on a game where users have to guess which quadrant a meteor will hit. After each round, I want to display an image of a "crater" on the map based on the randomly generated quadrant using PHP's rand(1,4) function. The map is represented a ...

Storing images either on files or in a database while utilizing docker

Currently working on a project utilizing Docker, with the primary goal being to ensure application availability even if one of the nodes in the 6-node cluster (using docker swarm) goes down. The core of the application is a Django App that handles image s ...

What is the process for adjusting the page orientation with javascript?

I am in the process of creating a video site with fullscreen capabilities. My goal is to automatically switch the page orientation to landscape mode when it is accessed on a smartphone. I attempted to achieve this using css media orientation, but unfortuna ...

The close button on the modal is malfunctioning

I am currently facing an issue with a simple modal window that opens when a link is clicked and should close when the user clicks on the close button, represented as a red rectangle in my fiddle. You can access my fiddle through this link Below is the re ...

When incorporating inline-block styling in dompdf, it may result in added space below the elements

One issue that arises when there are multiple elements with display:inline-block is that these elements can sometimes display with a margin below them after being rendered as a PDF: <div style="background-color:pink;"> <div style="background- ...

Select any menu option to return to the one-page layout and then scroll down to find the location

I'm wondering if there is a way to navigate back from an external page to a specific section on my one-page website with a fixed menu? On my one-pager website, I have a fixed menu that includes a "apply for a job" button. When clicked, it takes users ...

The username provided is required to be set in order to proceed

When attempting to register a user in my project, I encounter the following error: ValueError: The given username must be set The technologies used in my project include Django 1.11 and AngularJS 1.6 View.py def createUser(request): if request.me ...