0

I am trying to add contents to models.py dynamically using templates. For this i have the following line in views.py

model_content = render_to_string('myapp/models.txt',{'table':table_name, 'fields':fields})

models.txt in templates

class {{ table }}(models.Model):
{% for field in fields %}
   {{ field.field_name }} = models.{{ field.field_type.name }}
{% endfor %}

But when i wrote model_content string to a file say models.py i am getting the below

class Mytable(models.Model):

    order = models.CharField

    cust_name = models.CharField

I am getting an extra line after every line. How to avoid this. I will provide additional information if required.

Nitheesh MN
  • 608
  • 8
  • 18
  • I wrote something similar and created a template tag to strip the empty lines. https://github.com/allcaps/django-scaffold/blob/master/scaffold/templatetags/scaffold_tags.py You can also put your forloop on one line. But that makes it harder to read. Something like `{% for field in fields %} {{ field.field_name }} = ...` – allcaps Jan 31 '18 at 12:10
  • You could use Jinja2, which [has ways to control whitespace](https://stackoverflow.com/questions/35775207/remove-unnecessary-whitespace-from-jinja-rendered-template). – Alasdair Jan 31 '18 at 13:40

0 Answers0