Django中没有内容的PDF文件

时间:2017-04-23 16:09:59

标签: django django-models django-forms

更新

朋友你好

我想请你帮忙。

我创建了一个生成PDF文件的网络表单。一切都好。通过电子邮件自动发送PDF即可。遗憾的是,未添加到models.Model的表单字段不包含在PDF(内容)中。

PDF文档显示(postal_code)为空白字段。

我不知道该怎么办。问题在哪里?

model.py

class Order(models.Model):
    name = models.CharField(max_length=50)

forms.py

CHOICES=[('item1','1xx'),
         ('item2','2xx')]

class OrderCreateForm(forms.ModelForm):
    postal_code = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

    class Meta:
        model = Order
        fields = ['name', 'postal_code']

create.html上

  <form action="." method="post" class="order-form">
    {{ form.as_ul }}
    <p><input type="submit" value="Send"></p>
    {% csrf_token %}
  </form>

tasks.py

from celery import task
from django.shortcuts import get_object_or_404

from oferty.models import Order
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.conf import settings
import weasyprint
from io import BytesIO

@task
def order_created(order_id):

    order = Order.objects.get(id=order_id)
    subject = 'NEW {}'.format(order.id)
    message = 'Hi  {}!\n\nBlablabla.\
                  Ident blabla {}.'.format(order.imię,
                                            order.id)
    email = EmailMessage(subject,
                         message,
                         'admin@myshop.com',
                         [order.email])

    html = render_to_string('orders/order/pdf.html', {'order': order})
    out = BytesIO()
    stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
    weasyprint.HTML(string=html).write_pdf(out,
                                           stylesheets=stylesheets)
    email.attach('order_{}.pdf'.format(order.id),
                 out.getvalue(),
                 'application/pdf')


    email.send()

pdf.html

<html>
<body>
  <h1>Test</h1>
  <p>
    {{ order.name }}<br>
    {{ order.postal_code }}
  </p>
</body>
</html>

你能给我任何提示吗?

非常感谢您的帮助。

更新

views.py

from django.shortcuts import render
from .models import OrderItem
from .forms import OrderCreateForm
from cart.cart import Cart
from .tasks import order_created
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
from .models import Order
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
import weasyprint


def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(order=order,
                                        product=item['product'],
                                        price=item['price'],
                                        quantity=item['quantity'])
            cart.clear()
            order_created.delay(order.id)
            return render(request,
                          'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm()
    return render(request,
                  'orders/order/create.html',
                  {'cart': cart, 'form': form})


@staff_member_required
def admin_order_pdf(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    html = render_to_string('orders/order/pdf.html',
                            {'order': order})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename= "order_{}.pdf"'.format(order.id)
    weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')])
    return response

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^create/$',
        views.order_create,
        name='order_create'),
    url(r'^admin/order/(?P<order_id>\d+)/pdf/$',
        views.admin_order_pdf,
        name='admin_order_pdf'),
]

环境:

Django Version: 1.10.6
Python Version: 3.5.2

帮助。严重。

2 个答案:

答案 0 :(得分:2)

假设您要将邮政编码存储在订单上,您需要添加&#39; postal_code&#39; OrderCreateForm上的字段存在于Order模型中。

<强> models.py

  nlines <- 

  phis <- seq( 0, 2*pi, by=2*pi/nlines )
  rad  <- 999

  xs <- rad * cos( phis )
  ys <- rad * sin( phis )

之后,您只需要为您的模型表单指定该字段的无线电选择小部件。

<强> forms.py

class Order(models.Model):

    CHOICES = [
        ('item1', '1xx'),
        ('item2', '2xx')
    ]

    name = models.CharField(max_length=50)
    postal_code = models.CharField(max_length=50, choices=CHOICES)

答案 1 :(得分:1)

因为postal_code不是订单模型的字段。您必须单独传递它的值。或者您可以在模型中添加该字段。如果你选择不包括这可能有帮助。

from celery import task
from oferty.models import Order
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.conf import settings
import weasyprint
from io import BytesIO

@task
def order_created(order_id,postal_code):
    order = Oferta.objects.get(id=order_id)
    subject = 'New nr {}'.format(order.id)
    message = 'Hallow,  {}!\n\nBlaBlaBla.\
              BlaBlaBla {}.'.format(order.imię,
                                        order.id)
    email = EmailMessage(subject,
                     message,
                     'admin@myshop.com',
                     [order.email])

    html = render_to_string('orders/order/pdf.html', {'order': order,'postal_code':postal_code})
    out = BytesIO()
    stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]
    weasyprint.HTML(string=html).write_pdf(out,
                                       stylesheets=stylesheets)

    email.attach('order_{}.pdf'.format(order.id),
             out.getvalue(),
             'application/pdf')

    email.send()

使用两个值

调用该函数
order_created(order_id=order_id,postal_code= postal_code)

并在pdf.html替换

{{order.postal_code}}

{{postal_code}}