基于Django中的下拉选项在模板中预览表单

时间:2014-03-10 01:12:17

标签: python django django-forms

我正在开发一个预览HTML电子邮件的应用程序。

在初始创建页面上,我希望用户能够在提交之前预览电子邮件。

这是我到目前为止所拥有的

views.py

def mail_create(request):
    context = RequestContext(request)          
    if request.method == 'POST':
        form = MailForm(request.POST)         
        if form.is_valid():
          if '_preview' in request.POST:
              post = form.save(commit=False)
              context_dict = {}
              subject_line =  form.cleaned_data['subject_line']
              headline = form.cleaned_data['headline']
              mail_body = form.cleaned_data['mail_body']
              image = form.cleaned_data['image']
              context_dict = {} 
              context_dict['mail'] = mail
              context_dict['subject_line'] = subject_line
              context_dict['headline'] = headline
              context_dict['mail_body'] = mail_body
              context_dict['image'] = image 
              t = form.cleaned_data['template']
              preview = t.render(Context(context_dict))
              return HttpResponse(preview)
          elif '_save' in request.POST:
              form.save(commit=True)
              return HttpResponseRedirect(reverse('posta.mail'))
        else:
            print form.errors
    else:
        form = MailForm()       
    return render_to_response('mail_create.html', {'form' : form}, context)

forms.py

from django import forms
from posta.models import Mail, mail_template, Image
from django.contrib.auth.models import User

class MailForm(forms.ModelForm):
    name = forms.CharField(max_length=140, help_text="Please enter a name for your email.")
    subject_line = forms.CharField(max_length=140, help_text="Please enter the subject line for your email.")
    target = forms.CharField(max_length=140, help_text="Who is this email going to?")
    date_scheduled = forms.DateField(help_text="When do you need this email sent?",
                                     widget=forms.TextInput(attrs={'id':'datepicker'}))    
    template = forms.ModelChoiceField(queryset=mail_template.objects.all(), help_text="Select a Template")
    headline = forms.CharField(max_length=140, help_text="Please enter a headline for your email.")
    mail_body = forms.CharField(widget=forms.Textarea)
    image = forms.ModelChoiceField(queryset=Image.objects.all())

    class Meta:
        model = Mail
        fields = ('name','subject_line','target','date_scheduled','template', 'headline', 'image', 'mail_body')

单击预览按钮时,出现此错误 例外值:

'mail_template' object has no attribute 'render'

我应该使用渲染来响应吗?模板是来自表单模板选择的数据吗?

编辑:这是我的models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Mail(models.Model):
    DRAFT = 0
    READY = 1
    SENT = 2
    STATUS_CHOICES= ((DRAFT, 'Draft'),(READY, 'Ready'), (SENT, 'Sent'))
    name = models.CharField(max_length=140, unique=True)
    date_created = models.DateTimeField(auto_now=True)
    date_scheduled = models.DateField()
    target = models.CharField(max_length=140)
    template = models.ForeignKey('mail_template')
    subject_line = models.CharField(max_length=140)
    headline = models.CharField(max_length=140)
    mail_body = models.TextField()
    status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT)
    image = models.ForeignKey('Image')

    def __unicode__(self):
        return self.name


class Image(models.Model):
    image = models.ImageField(upload_to='gallery/')

class mail_template(models.Model):
    name = models.TextField()
    template_body = models.TextField()

    def __unicode__(self):
        return self.name

示例mail_template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>{{mail.subject_line}}</title>
</head>

<body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0" offset="0" style="-webkit-text-size-adjust:none; margin:0; padding:0; background-color:#FAFAFA; width:100%; ">
    <center>
        <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="backgroundTable" style="margin:0; padding:0; background-color:#FAFAFA; height:100%; width:100%; ">
            <tr>
                <td align="center" valign="top" style="border-collapse:collapse; ">
                    <table border="0" cellpadding="0" cellspacing="0" width="600" id="templateContainer" style="border:0; background-color:#FDFDFD; ">
                        <tr>
                            <td align="center" valign="top" style="border-collapse:collapse; ">
                                <table border="0" cellpadding="0" cellspacing="0" width="600" id="templateHeader" style="background-color:#FFFFFF; border-bottom:5px solid #505050; ">
                                    <tr>
                                        <td align="center" class="headerContent" style="border-collapse:collapse; color:#202020; font-family:Arial; font-size:34px; font-weight:bold; line-height:100%; padding:10px; text-align:center; vertical-align:middle; ">
                                            <div class="mktEditable" id="column_text1">
                                                <img title="{{mail.subject_line}}" src="{{ mail.image}}" alt="{{mail.subject_line}}" height="120" width="600">
                                            </div>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td align="center" valign="top" style="border-collapse:collapse; ">
                                <table border="0" cellpadding="10" cellspacing="0" width="600" id="templateBody">
                                    <tr>
                                        <td valign="top" class="bodyContent" style="border-collapse:collapse; background-color:#FDFDFD; ">
                                            <table border="0" cellpadding="10" cellspacing="0" width="100%">
                                                <tr>
                                                    <td valign="top" style="border-collapse:collapse; ">
                                                        <div mc:edit="std_content00" style="color:#505050; font-family:Arial; font-size:14px; line-height:125%; text-align:justify; ">
                                                            {{ mail.body }}
                                                        </div>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td align="center" valign="top" style="border-collapse: collapse;"></td>
            </tr>
        </table>
        <br>
    </center>

</body>

</html>

1 个答案:

答案 0 :(得分:0)

好的,这解释了事情。问题是你在任何时候都没有创建一个实际的Template对象。更改两行将修复它:

def mail_create(request):
    context = RequestContext(request)          
    if request.method == 'POST':
        form = MailForm(request.POST)         
        if form.is_valid():
          if '_preview' in request.POST:
              post = form.save(commit=False)
              # ...
              t = form.cleaned_data['template']
              tmpl = Template(t.template_body)             # <--
              preview = tmpl.render(Context(context_dict)) # <--
              return HttpResponse(preview)

确保from django.template import Template位于最前方。

BTW,mail_template.name应该是CharField