社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

Django验证电子邮件外键

Prosy Arceno • 4 年前 • 1893 次点击  

我有以下个人资料资源:

class ProfileResource(resources.ModelResource):
    email = fields.Field(attribute='email', 
        widget=CharWidget(), 
        column_name='email')

    class Meta:
        model = Profile
        clean_model_instances = True
        import_id_fields = ('email',)

在创建配置文件时验证电子邮件。它工作正常,但当我将其用作外键时,例如:

class InvestmentResource(resources.ModelResource):
    email = fields.Field(attribute='email', 
        widget=ForeignKeyWidget(Profile, field='email'), 
        column_name='email')

    class Meta:
        model = Investment
        clean_model_instances = True
        import_id_fields = ('id',)

    def before_import_row(self, row, row_number=None, **kwargs):
        self.email = row["email"]
        self.profile__firstname = row["firstname"]
        self.profile__lastname = row["lastname"]

    def after_import_instance(self, instance, new, row_number=None, **kwargs):
        """
        Create any missing Profile entries prior to importing rows.
        """
        try:
            profile, created = Profile.objects.get_or_create(email=self.email)

            profile.firstname = self.profile__firstname
            profile.lastname = self.profile__lastname
            profile.save()

            instance.profile = profile

        except Exception as e:
            print(e, file=sys.stderr)

它不再验证电子邮件。我试着添加了两个小部件, ForeignKeyWidget 和 CharWidget 在 InvestmentResource ,但没用。

然后,我如何验证邮件中的邮件 投资资源 ?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133615
文章 [ 1 ]  |  最新文章 4 年前
Matthew Hegarty
Reply   •   1 楼
Matthew Hegarty    5 年前

问题是,您的“电子邮件”字段被视为查找键,而不是电子邮件地址。这可以通过自定义 ForeignKeyWidget 添加电子邮件验证。

正在发生的情况是,您正在导入一个投资资源,这可能类似于:

email,firstname,lastname
bob@example.com,bob,smith

您已经配置了 InvestmentResource 将电子邮件用作 Profile .这意味着 django-import-export 不会将其作为电子邮件地址处理,而是作为 轮廓 ,所以在代码中( 外键控件 )它将做一些类似的事情:

Profile.objects.get(email='bob@example.com')

如果这是成功的,你的 Investment 实例现在将具有正确的配置文件作为外键引用。

这将引起一场争论 DoesNotExist 如果关联的 轮廓 他不在场。因此,您可以争辩说,csv中发送的电子邮件地址必须有效,因为如果无效,则无法查找。

但是,如果要在尝试加载之前检查电子邮件的语法是否有效 轮廓 ,那么这很容易做到,你需要覆盖 外键控件 要首先执行验证,请执行以下操作:

from django.core.exceptions import ValidationError
from django.core.validators import validate_email

class ValidatingForeignKeyWidget(widgets.ForeignKeyWidget):

    def clean(self, value, row=None, *args, **kwargs):
        
        try:
            validate_email(value)
        except ValidationError as e:
            # a quirk of import-export means that the ValidationError 
            # should be re-raised
            raise ValueError(f"invalid email {e}")
    
        try:
            val = super().clean(value)
        except self.model.DoesNotExist:
            raise ValueError(f"{self.model.__name__} with value={value} does not exist")
        return val