[英]django create user method in model
Hi I'm new to django and python. 嗨,我是django和python的新手。 I want to extend django User
model and add a create_user
method in a model, then I call this create_user
method from view. 我想扩展django User
模型并在模型中添加一个create_user
方法,然后从视图中调用此create_user
方法。 However, I got an error msg. 但是,我收到一个错误消息。
My model: 我的模特:
from django.db import models
from django.contrib.auth.models import User
class Basic(models.Model):
user = models.OneToOneField(User)
gender = models.CharField(max_length = 10)
def create_ck_user(acc_type, fb_id,fb_token):
# "Create a user and insert into auth_user table"
user = User.objects.create_user(acc_type,fb_id,fb_token)
user.save()
class External(models.Model):
user = models.OneToOneField(Basic)
external_id = models.IntegerField()
locale = models.CharField(max_length = 40)
token = models.CharField(max_length = 250)
and in view, I did sth like this: 而且,我确实是这样的:
Basic.create_ck_user('acc_type' = 'fb', 'fb_id' = fb_id, 'fb_token' = fb_token)
error shows that: 错误显示:
keyword can't be an expression (views.py, Basic.objects.create_ck_user('acc_type' = 'fb', 'fb_id' = fb_id, 'fb_token' = fb_token))
Edit: After add @classmehtod, and change view.py to: 编辑:添加@classmehtod,并将view.py更改为:
...
if (request.method == 'POST'):
acc_type = request.POST.get('acc_type')
fb_id = request.POST.get('fb_id')
fb_token = request.POST.get('fb_token')
Basic.create_ck_user(acc_type,fb_id,fb_token)
...
An error msg shows: 错误消息显示:
create_ck_user() takes exactly 3 arguments (4 given) create_ck_user()恰好接受3个参数(给定4个)
checked error details, it includes "request" variable though that i just pass 3 variables: acc_type
, fb_id
and fb_token
. 检查错误的详细信息,尽管我只传递了3个变量: acc_type
, fb_id
和fb_token
,但它包括“ request”变量。
Any ideas? 有任何想法吗?
Try 尝试
Basic.create_ck_user('fb', fb_id, fb_token)
You don't assign to strings when you call a function/method. 调用函数/方法时,您不会分配给字符串。 You assign to variables. 您分配给变量。 But since you are using positional arguments in your function definition then you don't even need them. 但是,由于在函数定义中使用了位置参数,因此甚至不需要它们。
Assigning to a string will never work anyway... strings are immutable objects. 分配字符串永远是行不通的……字符串是不可变的对象。
Also, you want this method to be a class method. 另外,您希望此方法成为类方法。 Otherwise you would need to create an instance of User before calling it. 否则,您需要在调用User之前创建一个User实例。
# inside class definition
@classmethod
def create_ck_user(cls, acc_type, fb_id,fb_token):
# "Create a user and insert into auth_user table"
user = cls.objects.create_user(acc_type,fb_id,fb_token)
user.save()
Just look here: https://docs.djangoproject.com/en/dev/topics/auth/default/#creating-users 只需查看此处: https : //docs.djangoproject.com/en/dev/topics/auth/default/#creating-users
You can find a lot of answers just looking at the documentation. 仅查看文档即可找到很多答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.