0

在我用户的数据编辑表单中,我有一个布尔字段,用于从时事通讯中添加/删除电子邮件。我为此表单编写了一个自定义保存方法:

def save(self, *args, **kwargs):      
    mail = None
    if self.cleaned_data['inf_newsletter']:
        mail = NewsletterEmails(self.instance.user.email)
        mail.save() 
    else:
        try:
            mail = NewsletterEmails.objects.get(email=self.instance.user.email)
        except NewsletterEmails.DoesNotExist:
            pass
        if mail:
            mail.delete()

问题是,当我添加新的 NewsletterEmail 对象时,我正在发送从用户电子邮件中读取的字符串值以保存在电子邮件字段中,这会引发错误(或者至少我认为是这样):

Traceback:
File "/home/myapp/site-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/home/myapp/site-packages/django/contrib/auth/decorators.py" in __call__
  78.             return self.view_func(request, *args, **kwargs)
File "/home/myapp/accounts/views.py" in profile_edit
  95.             form.save()
File "/home/myapp/accounts/forms.py" in save
  58.             mail.save() 
File "/home/myapp/site-packages/django/db/models/base.py" in save
  410.         self.save_base(force_insert=force_insert, force_update=force_update)
File "/home/myapp/site-packages/django/db/models/base.py" in save_base
  470.                         manager.filter(pk=pk_val).extra(select={'a': 1}).values('a').order_by())):
File "/home/myapp/site-packages/django/db/models/manager.py" in filter
  129.         return self.get_query_set().filter(*args, **kwargs)
File "/home/myapp/site-packages/django/db/models/query.py" in filter
  498.         return self._filter_or_exclude(False, *args, **kwargs)
File "/home/myapp/site-packages/django/db/models/query.py" in _filter_or_exclude
  516.             clone.query.add_q(Q(*args, **kwargs))
File "/home/myapp/site-packages/django/db/models/sql/query.py" in add_q
  1675.                             can_reuse=used_aliases)
File "/home/myapp/site-packages/django/db/models/sql/query.py" in add_filter
  1614.                 connector)
File "/home/myapp/site-packages/django/db/models/sql/where.py" in add
  56.                 obj, params = obj.process(lookup_type, value)
File "/home/myapp/site-packages/django/db/models/sql/where.py" in process
  269.                 params = self.field.get_db_prep_lookup(lookup_type, value)
File "/home/myapp/site-packages/django/db/models/fields/__init__.py" in get_db_prep_lookup
  210.             return [self.get_db_prep_value(value)]
File "/home/myapp/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
  361.         return int(value)

Exception Type: ValueError at /user/profile/
Exception Value: invalid literal for int() with base 10: 'foo@bar.com'

我的时事通讯电子邮件模型:

class NewsletterEmails(models.Model):
    email = models.EmailField(_(u"Email"),)

如何解决这个问题?

4

1 回答 1

3
mail = NewsletterEmails(self.instance.user.email)

您将输入的电子邮件地址分配给隐式创建的主键字段,而不是电子邮件字段。

利用:

mail = NewsletterEmails(email=self.instance.user.email)
于 2010-07-12T03:35:55.277 回答