[Django] AttributeError: ‘module’ object has no attribute ‘TextField’

[Django] AttributeError: ‘module’ object has no attribute ‘TextField’

We can define the TextField in the Django model. But, there is no TextField type in the Django form.

This Django implementation is really strange for many of the developers. I’m not sure about it. But, there is a way to sort it out.

Let’s start with creating Django model and form for text data.

How to Create TextField in Django Model and Form?

You can create the TextField in the Django model by adding the following line of code in models.py.

For example:

note = models.TextField(default='', blank=True)

Here “note” is the model variable name which has type TextField.

Now, you want to use this field for creating a form so that the user can insert text data through the Django form.

Let’s try creating TextField in Django form by updating forms.py.

note = forms.TextField(required=False)

When you run your Django application, it will throw an error as

AttributeError: 'module' object has no attribute 'TextField'

This is because, there is no attribute as the TextField associated with the module forms.

Use the CharField in the Django form instead of TextField.

note = forms.CharField(required=False, widget=forms.Textarea)

We are also setting a widget attribute for the Django form. It can replicate the behavior of TextField in the Django model.

Django is very beautiful for creating websites and it is widely adopted in the software industry for the reason.

In this tutorial, we have learned to create the Django form with the TextField data by solving AttributeError exception. If you have any doubt, let me know in the comment. Keep learning.


Leave a Reply

Your email address will not be published. Required fields are marked *