2017-09-30 73 views
0

每當創建新的用戶實例時,我想創建一個與其關聯的配置文件實例。 要做到這一點,我試圖使用信號。保存後信號不會在Django中調用

這裏的代碼models.py:

@receiver(post_save, sender=User) 
def create_user_profile(sender,**kwargs): 
    print(sender) 

這裏從view.py是:

@api_view(["POST"]) 
def register(request): 
    username = request.data.get("username") 
    first_name = request.data.get("first_name") 
    last_name = request.data.get("last_name") 
    email = request.data.get("email") 
    password1 = request.data.get("password1") 
    password2 = request.data.get("password2") 

    user = User.objects.create_user(username,email,password1) 

    if user: 
     user = authenticate(username=username, password=password1) 

    if not user: 
     return Response({"error": "Login failed"}, status=HTTP_401_UNAUTHORIZED) 

    token, _ = Token.objects.get_or_create(user=user) 
    return Response({"token": token.key}) 

但是,創建新用戶時沒有被打印到我的終端。

編輯:讓我感動的功能signals.py和編輯apps.py但它仍然沒有工作:

from django.apps import AppConfig 

class AuthConfig(AppConfig): 
    name = 'auth' 
    verbose_name = 'Auth Application' 

    def ready(self): 
     from . import signals 

和這裏的__init__.py

default_app_config = 'auth.apps.AuthConfig' 
+0

什麼是您的models.py中的create_user_profile函數的位置 – iklinac

+0

@iklinac在Profile模型類的正下方 – dpstart

+0

@dpstart它必須位於用戶模型下方而不是Profile Model或(如我所願)應位於單獨的偵聽器文件中通過AppConfig正確鏈接 – kushj

回答

-1

一般的問題是signals.py不是招」 t已導入,you need to add it to your AppConfig正如評論中提到的:

# apps.py 

# or whatever the class is called inside the app containing signals.py 
class RegistrationConfig(AppConfig): 
    name = 'registration' 

    # This is the piece you will need to add 
    def ready(self): 
     from . import signals 
+0

我做到了這一點,但它無法正常工作(我編輯了這個問題) – dpstart

+0

確保在你的settings.py文件中,你使用apps.py配置類來安裝軟件包,而不是模塊本身。這意味着 INSTALLED_APPS = [「module.apps.RegistrationConfig」] – jonzlin95

+0

這不是必需的。此外,您的鏈接到Django文檔並沒有這樣說。 – olieidel