1👍
✅
First, you don’t need to set null=False, blank=False
on your title
field as those are there by default.
It looks like the main issue you’re having is adding the Bootstrap css class to the form element, which you can accomplish a couple of different ways. Also note that your value
attribute is missing quotes around it.
The first way is to add the appropriate classing to the widget from the Python side of the form:
class QuestionsForm(forms.ModelForm):
class Meta:
model = Questions
fields = ('title', )
def __init__(self, *args, **kwargs):
super(QuestionsForm, self).__init__(*args, **kwargs)
self.fields['title'].widget.attrs['class'] = 'form-control'
However, this gets really tedious when you’re dealing with a lot of form fields. So, I use django-widget-tweaks to instead add these at the template level:
{{ form.title|add_class:"form-control" }}
which I find a lot easier to deal with. This way you don’t have to render the field by hand. Also be sure to handle the case if there’s no matching question in your view:
question = get_object_or_404(Question, id=pk)
Source:stackexchange.com