我正在使用Python(3.7)和Django(2.1)开发一个项目,在该项目中,我需要在创建用户时创建用户个人资料。
这是我尝试过的:
来自models.py
:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.CharField(max_length=500, null=True)
about = models.CharField(max_length=1000, null=True)
slogan = models.CharField(max_length=500, null=True)
profile_pic = models.FileField(upload_to='media/profile_pics', null=True)
def __str__(self):
return self.user.username
来自signals.py
:
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, created, **kwargs):
instance.profile.save()
来自urls.py
:
path('register/', views.RegisterUser.as_view(), name='register'),
来自views.py
:
def post(self, request, *args, **kwargs):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account has been created for {username}!')
form.save()
return HttpResponseRedirect(reverse_lazy('login'))
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
来自forms.py
:
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('username', 'email', 'first_name',
'last_name', 'password1', 'password2')
来自apps.py
:
class JobexpertappConfig(AppConfig):
name = 'jobexpertapp'
app_label = 'jobexpertapp'
def ready(self):
import jobexpertapp.signals
更新: 我还通过使用
django-social-auth
在我的网站上使用了facebook身份验证,并且为了获取facebook头像,我实现了2件事,(a)定义了social_auth_pipeline.py
(b):添加SOCIAL_AUTH_PIPELINE
在settings.py
中:
所以
来自social_auth_pipeline.py
:
def save_avatar(backend, user, response, *args, **kwargs):
try:
profile = Profile.objects.get(user_id=user.id)
except Profile.DoesNotExist:
profile = Profile(user_id=user.id)
if backend.name == 'facebook':
profile.avatar = 'http://graph.facebook.com/{}/picture?type=large'.format(response['id'])
profile.save()
来自settings.py
:
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.auth_allowed',
'social.pipeline.social_auth.social_user',
'social.pipeline.user.get_username',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
# 'apps.users.pipeline.get_avatar',
'jobexpertapp.social_auth_pipeline.save_avatar',
)
当我通过注册页面创建新帐户时,它会创建user
,但不会创建配置文件。
另外,创建用户时在控制台上找不到任何错误。
这里有什么问题吗?
谢谢!
答案 0 :(得分:1)
我遇到了同样的问题。
我的信号在类UsersConfig(AppConfig)中的'users'/'apps.py'中:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/styleliste.css' %}">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head>
<title>{% block title %}Liste des Raspberry Pi{% endblock %}</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body class="bg2">
<ul>
<li><a href="/page/accueil/">Accueil</a></li>
<li><a href="/page/ListRPI/">Liste des Raspberry PI</a></li>
<li><a href="/page/Info/">Plus d'informations</a></li>
<li><a class="active">Raspberry PI {{rpi_id}}</a></li>
</ul>
<section id="contentinfo">
<div id="update">
{% include 'page/update.html' %}
</div>
<div>
<form method="POST" >
{% csrf_token %}
{{ form.as_p }}
<input class="ml-button-3" type="submit" value="Envoyer message"/>
</form>
<form method ="POST" enctype="multipart/form-data">
{% csrf_token %}
<input class="ml-button-3" type="submit" name="btn" value="Start" />
<input class="ml-button-3"type="submit" name="btn" value="Stop" />
<input class="ml-button-3"type="submit" name="btn" value="Reboot" />
<input class="ml-button-3" type="submit" name="btn" value="Code" /> <br><br>
<input type="file" name="myfile">
<input class="ml-button-3" type="submit" name = "btn" value="Envoyer code"></button>
</form>
</div>
</section>
<script>
$.ajax({
url: 'http://localhost:8000/page/RPI/1/',
success: setInterval(function(){
alert('Vote successful!');
$("#update").load("update.html");
},5000)
});
</script>
</body>
</html>
对我有用的是以下内容。在INSTALLED_APPS列表的project /'settings.py'中,我曾经用自己的名字(即“博客”,“用户”)列出我的应用程序。当我对此进行更改并改为这样列出它们时:“ blog.apps.BlogConfig”,“ users.apps.UsersConfig”,配置文件创建/保存在用户创建/保存时触发,因此可以正常工作。