Django通用视图更新 - 如果表单已保存则发送电子邮件 - 如何?

时间:2012-02-23 19:47:26

标签: django django-views

我有这个UpdateView子类

class UpdateShipView(UpdateView):
    form_class = CruiseShipForm
    template_name = 'cruise/ship_form.html'
    success_url = 'cruise/ships'

    def get_object(self, queryset=None):
        obj = CruiseShip.objects.get(pk=self.kwargs['ship_id'])
        return obj

我想通过以下代码向某些人发送电子邮件:

def form_valid():
    msg = 'bla bla'    
    send_mail('Cruise Ship change: ', msg, 'offer_entry@ensembletravel.com',
        user_emails, fail_silently=False)
    return super(UpdateShipView, self).form_valid()

我收到此错误:

Django Version: 1.3.1
Exception Type: TypeError
Exception Value:    form_valid() takes no arguments (2 given)

我相信我需要重新编写form_valid()方法,但此时我还没有看到一个指导我的例子

2 个答案:

答案 0 :(得分:0)

UpdateView对象的form_valid方法必须有参数" form"。此方法的定义必须是:

def form_valid(self, form):
    ....

答案 1 :(得分:0)

我想跟进我最终的工作。

import django.contrib.auth as auth
from django.core.mail import send_mail

def form_valid(self, form):
    group = auth.models.Group.objects.get(name='cruise')
    users = group.user_set.all()
    user_emails = []
    for u in users:
        user_emails.append(u.email)
        print u.username, u.email
    cruise_ship = self.get_object()
    msg = "%s (%d) has changed."% (cruise_ship.name, cruise_ship.shipid)
    msg += "\nYou can review it here: http://localhost:8000/cruise/ships/%d/" % cruise_ship.shipid
    # print user_emails  #for debug
    send_mail('Cruise Ship change: ' + cruise_ship.name, msg, 'offer_entry@ensembletravel.com',
        user_emails, fail_silently=False)
        #context = super(PublisherDetailView, self).get_context_data(**kwargs)

    return super(UpdateShipView, self).form_valid(form)