Home > Software design >  Fill data from database to Word (Django Python)
Fill data from database to Word (Django Python)

Time:11-15

I don't know how to get data and fill into my word template. It's actually a long list, and I need to fill it on my table on word document. Am I doing it right? Here is my code:

views.py

def save_sample_details(request):
    sample = SampleList.objects.all()
    doc = DocxTemplate("lab_management/word/sample_template.docx")

    context = {
        'SNAME' : sample.sample_name,
        'STYPE' : sample.sample_type,
        'HVER' : sample.hardware_version,
        'SVER' : sample.software_version,
        'CS' : sample.config_status,
        'NUM' : sample.number,
        'SNUM' : sample.sample_number,
    }

    doc.render(context)
    doc.save('lab_management/word/sample.docx')

    return redirect('/lab/sample/details/')

models.py

class SampleList(models.Model):
    sample_name = models.CharField(max_length=32)
    sample_type = models.CharField(max_length=32)
    hardware_version = models.CharField(max_length=32)
    software_version = models.CharField(max_length=32)
    config_status = models.CharField(max_length=18)
    number = models.IntegerField(default=0)
    sample_number = models.CharField(max_length=17)

So if I run this, it shows 'QuerySet' object has no attribute 'sample_name' etc.

CodePudding user response:

You're getting all SampleList objects when you call SampleList.objects.all() so this is returning a QuerySet of zero or more objects, rather than a single object - which is what you want.

Instead you should get the single SampleList object you want: for example sample = SampleList.objects.get(id=1) or another example - to get the first object in the QuerySet you could do sample = SampleList.objects.all()[0] (but if the QuerySet is empty you'll get an index error). You didn't specify how you want to determine which SampleList to put in the Word doc, but you can specify any filters in the .get() properties.

Django has some pretty good documentation covering querysets: https://docs.djangoproject.com/en/4.1/ref/models/querysets/

CodePudding user response:

Change your code as:

def save_sample_details(request):
    sample_list = SampleList.objects.all()
    doc = DocxTemplate("lab_management/word/sample_template.docx")

    context_list = []
    for sample in sample_list:
        context = {
            'SNAME' : sample.sample_name,
            'STYPE' : sample.sample_type,
            'HVER' : sample.hardware_version,
            'SVER' : sample.software_version,
            'CS' : sample.config_status,
            'NUM' : sample.number,
            'SNUM' : sample.sample_number,
        }
        context_list.append(context)

    doc.render(context_list)
    doc.save('lab_management/word/sample.docx')

    return redirect('/lab/sample/details/')

You should be iterating in the context_list in the doc as well.

(Assuming you are using docxtpl library)

  • Related