Issue
I am very new to Django. Following some tutorials I have managed to create a form using the Python Generic Views (CreateView)
I have a 'Question' Model
class Question(models.Model):
title = models.CharField(max_length=200)
body = models.TextField(max_length=2000)
category = models.CharField(max_length=50)
votes = models.IntegerField(default=0)
asked_date = models.DateTimeField(default=datetime.now)
and using this model I have created a View Class
class QuestionCreate(CreateView):
model = Question
fields = ['title', 'body', 'category']
This does generate a nice HTML form. But how do I pass CSS attributes to each field?
Solution
You could write a model form for Question and pass it to the create view,
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ('myfield1', 'myfield2)
widgets = {
'myfield1': forms.TextInput(attrs={'class': 'myfieldclass'}),
}
or you could override init method for specifying a certain class for every field,
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield1'].widget.attrs.update({'class' : 'myfieldclass'})
Then, pass it to the attribute form_class
of CreateView
,
class QuestionCreate(CreateView):
model = Question
form_class = QuestionForm
Answered By - zaidfazil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.