Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Applying a custom id/class/name to a formfield

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?

like image 438
user1115304 Avatar asked Feb 10 '12 01:02

user1115304


2 Answers

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" />
like image 76
Aamir Rind Avatar answered Sep 20 '22 15:09

Aamir Rind


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

like image 33
educalleja Avatar answered Sep 21 '22 15:09

educalleja