Python 将id参数传递到Django中导入的类中

Python 将id参数传递到Django中导入的类中,python,django,Python,Django,在Django中,我有一个基于函数的视图,负责在pdf文件中打印所有注册用户的详细信息(实际上只是名称) def test_pdf(request, id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = '

在Django中,我有一个基于函数的视图,负责在pdf文件中打印所有注册用户的详细信息(实际上只是名称)

def test_pdf(request, id):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="My Users.pdf"'

    buffer = io.BytesIO()

    report = MyPrint(buffer, 'Letter', id)
    pdf = report.print_users()

    response.write(pdf)
    return response
此函数之所以有效,是因为我在views.py文件中导入了另一个文件中构建的类,该类负责绘制pdf,MyPrint:

from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER
from django.contrib.auth.models import User


class MyPrint:
    def __init__(self, buffer, pagesize):
        self.buffer = buffer
        if pagesize == 'A4':
            self.pagesize = A4
        elif pagesize == 'Letter':
            self.pagesize = letter
            self.width, self.height = self.pagesize
    def print_users(self):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
        rightMargin=72,
        leftMargin=72,
        topMargin=72,
        bottomMargin=72,
        pagesize=self.pagesize)
        # Our container for 'Flowable' objects
        elements = []

        # A large collection of style sheets pre-made for us
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        users = User.objects.all()
        elements.append(Paragraph('My User Names', styles['Heading1']))
        for i, user in enumerate(users):
            elements.append(Paragraph(user.get_full_name(), styles['Normal']))

        doc.build(elements)

        # Get the value of the BytesIO buffer and write it to the response.
        pdf = buffer.getvalue()
        buffer.close()
        return pdf

现在,如果我将相对pk传递到函数中,如何使函数和类特定于用户?除了更新urlpattern外,我是否应该将id传递到类和/或函数中?

如果您希望现有函数与一个或多个用户一起工作,并且如果您不传递id,则继续工作,我认为最简单的更改方法如下:

def print_users(self, id=None):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
        rightMargin=72,
        leftMargin=72,
        topMargin=72,
        bottomMargin=72,
        pagesize=self.pagesize)
        # Our container for 'Flowable' objects
        elements = []

        # A large collection of style sheets pre-made for us
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        users = User.objects.all()
        if id:
            users = users.filter(id__in=id)
        elements.append(Paragraph('My User Names', styles['Heading1']))
        for i, user in enumerate(users):
            elements.append(Paragraph(user.get_full_name(), styles['Normal']))

        doc.build(elements)

        # Get the value of the BytesIO buffer and write it to the response.
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
然后将其命名方式更改为:

report = MyPrint(buffer, 'Letter')
pdf = report.print_users(id)
或者,如果要打印所有用户,只需将其称为:

report = MyPrint(buffer, 'Letter')
pdf = report.print_users()

什么是
test\u pdf
中的
id
?我没有定义它…因为我认为它会在MyPrint类中定义自己。你必须解释你想要做什么。MyPrint是一个普通的python类,因此如果您想在初始化时将其传递给特定用户,请将其作为参数添加到-init-method中。我将传递用户对象,而不是id。顺便说一句,这样您的视图可以处理id不正确(与用户不匹配)的情况,因此,您将执行uuu init_uuuu(self,buffer,pagesize,id),然后执行self.id=user.objects.get(id=id)?我试过它不工作…id必须是在文件view.pyWorks中的函数中传递的id!但是我不理解id=None,为什么要这样做?这是一个默认参数。这意味着如果您不传递
id
,它将默认值为
None
。查看更多信息。谢谢。但是为了打印所有用户/单个用户,我需要在视图中创建两个函数,对吗?否则,如果我不传递任何id参数,django会根据我在url.py(/testpdf)中声明的urlpattern抛出异常,您也可以向视图添加默认参数。然后您只需要有两个URL,都指向同一个视图。完全明白。如果将默认参数添加到视图中,则在类方法中不需要(但也没有坏处)默认参数。