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?
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" />
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With