Django: Applying a custom id/class/name to a formfield
Asked Answered
F

2

8

I've got a model that has the following code:

class PhillyCheese(models.Model):
    description = models.CharField(blank=True, max_length=255)
    quality = models.CharField(blank=True, max_length=255)
    packing_date = models.DateField(blank=True, null=True)
    shipping_date = models.DateField(blank=True, null=True)
    taste = models.CharField(blank=True, max_length=255)

and a form:

class PhillyCheeseForm(forms.ModelForm):
    class Meta:
        model = PhillyCheese

I'm attempting to apply a jquery datepicker to the two DateFields in the model. Only thing is, I would like to be precise on which field it goes to. Modifying the template is not an option; I have many other possible forms that are rendered through that template.

Could anybody please show me how to add a custom id/class/name so I can accurately identify the DateFields using Jquery?

Fate answered 10/2, 2012 at 1:27 Comment(0)
E
8

When creating forms you can pass attrs (dictionary based) to your particular field which then use those as attributes for field.

from django import forms
date = forms.DateInput(attrs={'size': 10, 'id': 'date_field',})
print date.render('date', '')

#This will produce:
#<input type="text" id="date_field" name="date" size="10" />
Emunctory answered 10/2, 2012 at 5:19 Comment(0)
S
6

You can find your solution in Django's documentation: https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#overriding-the-default-fields

In your case, your code would be something like this:

from django import forms

class PhillyCheeseForm(forms.ModelForm):
    class Meta:
        model = PhillyCheese
        widgets = {
            'packing_date': forms.TextInput(attrs={'id':'foo', 'name':'foo'})
            'shipping_date': forms.TextInput(attrs={'id':'bar', 'name':'bar'})
    }

I actually do not know if there is a way to avoid repeating the new field identifier in the id and name attributes.

EDIT:

Link to documentation of Django 2.1: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#overriding-the-default-fields

Spermicide answered 12/9, 2015 at 6:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.