How to create simple custom field in django?

141 Views Asked by At

I want to create two additional properties of TextField such as property1 and property2 so that I can access them in template like

{% for field in form %}
  {{ field.property1 }}
  {{ field.property2 }}
{% endfor %}

my current model looks like

class ResponseModel(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ans1 = models.TextField()
    ans2 = models.TextField()
    submit_count = models.IntegerField(default=0)

    def __str__(self):
        return str(self.author) + str(self.submit_count)
1

There are 1 best solutions below

1
On

in order to access the model properties in the template you should pass them through the view.py:

**views.py**

from .models import *

def index(request):
   context={
      'form': ResponseModel
   }

   return render(request, 'path/to/template', context)

And in index.html (Template):

{% for field in form %}
   {{ field.property1 }}
   {{ field.property2 }}
{% endfor %}

That should work just fine, let me know if you got it.