带有社交授权的Django:禁止直接分配到多对多集合的前端



当尝试在Django中验证(创建(用户时,我得到以下错误:

Direct assignment to the forward side of a many-to-many set is prohibited. Use posts.set() instead.

我知道在Stack溢出上也有类似的问题,根据文档:

[模型]需要具有字段"的值;id";在可以使用这种多对多关系之前。。。。在保存之前,无法将其关联。

但是,由于我使用的是Python Social Auth,它在后端创建用户,所以我以后无法保存用户和修改字段。(尽管就我个人而言,在第一次创建用户时,我不需要在多对多字段中添加任何内容(

这是我的代码:

型号.py

...
from waters.models import Water
class User(AbstractUser):
    id = models.AutoField(primary_key=True)
    posts = models.ManyToManyField(Water) # MANY TO MANY FIELD CAUSING ERROR
...

oauth.py

from social_core.backends.oauth import BaseOAuth2
class <name>Oauth2(BaseOAuth2):
    name = "<name>"
    AUTHORIZATION_URL = "<url>"
    ACCESS_TOKEN_URL = "<url>"
    ACCESS_TOKEN_METHOD = "POST"
    EXTRA_DATA = [("refresh_token", "refresh_token", True), ("expires_in", "expires")]
    def get_scope(self):
        return ["read"]
    def get_user_details(self, response):
        profile = self.get_json("<url>", params={"access_token": response["access_token"]})
        return {
            "id": profile["id"],
            "username": profile["username"],
            ...
        }
    def get_user_id(self, details, response):
        return details["id"]

如何在不修改任何社交身份验证源文件的情况下解决此错误?

我能够通过扩展社会身份验证管道(文档(来绕过错误。首先,我制定了一个方法来适当地创建用户以绕过错误(如问题中链接的答案所述(:

身份验证/管道.py

from authentication.models import User
def create_user(backend, user, response, *args, **kwargs):
    u = User()
    for k, v in kwargs["details"].items():
        setattr(u, k, v)
    u.save()
    # Optionally update many to many field here

并在社交认证的create_user方法之前将其丢弃

设置.py

...
SOCIAL_AUTH_PIPELINE = (
    "social_core.pipeline.social_auth.social_details",
    "social_core.pipeline.social_auth.social_uid",
    "social_core.pipeline.social_auth.auth_allowed",
    "social_core.pipeline.social_auth.social_user",
    "social_core.pipeline.social_auth.associate_by_email",
    "authentication.pipeline.create_user", #ADDED
    "social_core.pipeline.user.create_user",
    "social_core.pipeline.social_auth.associate_user",
    "social_core.pipeline.social_auth.load_extra_data",
)
...

相关内容

  • 没有找到相关文章

最新更新