0
votes

First time posting on here and new to Django, sorry in advance.

Im trying to plug the name field from my model into my html template, which I will then convert to a pdf.

Everything involving the html to pdf conversion is working, I just cant seem to get the name field from my model to work into the html_template when it renders.

Ive tried adding 'name' : name into the context_dict within the render_to_pdf view, and that did not work.

I think I am likely missing something in my view.

pdf_template.html

{% block content %}
   <div class="container">
       <div class="row">

               <p> **{{name}}** </p>
               
   </div>
{% endblock %}

models.py

class User(models.Model):

    username = models.CharField(max_length = 20, primary_key=True)
    name = models.CharField(max_length = 20)
    
    def __str__(self): 
        return self.name

views.py

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None
2
Do you have a model object you want to display in your template or do you want a form that will create a model object ?RaoufM

2 Answers

0
votes

It's unclear what you're trying to do/ask.

If you want to list out all the user names, you can do this :

def listView(req):
    users = User.objects.all
    return render(request, 'home.html', {'names': users})

And then in your template :

<div class="container">
{% for name in names%}
        <p>{{ name.username }}</P       
</div>
0
votes

This is how you'd need to structure your function and call it with your current design. If name was none or an empty string, it wouldn't appear.

def render_to_pdf(template_src, context_dict=None):
    if context_dict is None:
        context_dict = {}
    template = get_template(template_src)
    html  = template.render(context_dict)
    ...


render_to_pdf('template/path/...', {'name': "some name"})