django 在创建用户时在 userprofile table 中创建一行
django creating a row in userprofile table when a user is created
我正在按照这个 (https://www.django-tips.com/tutorial/django-tutorial-with-twitter-app/1/?page=3) 教程使用 Django 创建一个 Twitter 克隆应用程序。但是在项目中,用户会通过django默认的用户创建系统来创建。
问题是,我想在创建用户时在用户配置文件 table 中创建一行。否则用户正在创建,我必须将其插入用户配置文件 table bu 访问项目的管理部分。我该怎么做?
模型看起来像这样:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
relation = models.ManyToManyField(
'self',
through='Relation',
symmetrical=False,
related_name='related_to',
default=None
)
def __unicode__(self):
return self.user.get_full_name()
class Relation(models.Model):
follower = models.ForeignKey(UserProfile, related_name='follows')
is_followed = models.ForeignKey(UserProfile, related_name='followers')
follow_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return '%s follows %s' % (self.follower.user.username, self.is_followed.user.username)
class Meta:
unique_together = ('follower', 'is_followed')
并且教程中也提到了创建一个信号,但是他们还没有清除这个文件的创建位置,所以我按照官方文档创建了 signals.py 文件。
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=user)
post_save.connect(create_profile, sender=User)
所以,我卡在了这个阶段,无法前进。提前致谢。
您不必创建信号文件...就在 UserProfile
之后
from django.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
....
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
要在创建用户后(通过 models.py)在用户配置文件 table 中创建一行,您可以从管理界面或 shell 或在前面创建一个表单-结束然后发布并保存它。 (我正在为您提供示例代码 - 其中的各种属性现在可能对您没有用。仅供您理解)。
shell 方法可以是这样的:
$ ./manage.py shell
>>> from django.contrib.auth import User
>>> from <package_profile>.models import UserProfile
>>> new_user = UserProfile(user_auth = new_user, name = name,...) # other whatever fields you want
>>> new_user.save()
表单方法可以是这样的:
from django.shortcuts import render
from django.http import HttpResponse
from <package_profile>.models import USerProfile, Developer
from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
@login_required
def page(request):
if request.POST:
form = Form_inscription(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
login = form.cleaned_data['login']
password = form.cleaned_data['password']
# User auth details:-
new_user = User.objects.create_user(username = login, password = password)
new_user.is_active = True
new_user.email = email
new_user.first_name = name
new_user.save()
new_developer = Developer(user_auth = new_user, name = name, email = email)
new_developer.save()
return HttpResponse("Developer added")
else:
return render(request, create_developer.html', {'form' : form})
else:
form = Form_inscription()
return render(request,create_developer.html', {'form' : form})
class Form_inscription(forms.Form):
name = forms.CharField(label="Name", max_length=30)
login = forms.CharField(label = "Login")
email = forms.EmailField(label = "Email")
password = forms.CharField(label = "Password", widget = forms.PasswordInput)
password_bis = forms.CharField(label = "Password Re-enter", widget = forms.PasswordInput)
def clean(self):
cleaned_data = super(Form_inscription, self).clean()
password = self.cleaned_data.get('password')
password_bis = self.cleaned_data.get('password_bis')
if password and password_bis and password != password_bis:
raise forms.ValidationError("Passwords are not identical.")
return self.cleaned_data
表格的对应 html 将是:
{% extends "base.html" %}
{% block title_html %}
Create Developer/User
{% endblock %}
{% block h1 %}
Create Developer
{% endblock %}
{% block article_content %}
<form method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<p><input type="submit" value="Create" /></p>
</form>
{% endblock %}
我正在按照这个 (https://www.django-tips.com/tutorial/django-tutorial-with-twitter-app/1/?page=3) 教程使用 Django 创建一个 Twitter 克隆应用程序。但是在项目中,用户会通过django默认的用户创建系统来创建。
问题是,我想在创建用户时在用户配置文件 table 中创建一行。否则用户正在创建,我必须将其插入用户配置文件 table bu 访问项目的管理部分。我该怎么做?
模型看起来像这样:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
relation = models.ManyToManyField(
'self',
through='Relation',
symmetrical=False,
related_name='related_to',
default=None
)
def __unicode__(self):
return self.user.get_full_name()
class Relation(models.Model):
follower = models.ForeignKey(UserProfile, related_name='follows')
is_followed = models.ForeignKey(UserProfile, related_name='followers')
follow_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return '%s follows %s' % (self.follower.user.username, self.is_followed.user.username)
class Meta:
unique_together = ('follower', 'is_followed')
并且教程中也提到了创建一个信号,但是他们还没有清除这个文件的创建位置,所以我按照官方文档创建了 signals.py 文件。
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=user)
post_save.connect(create_profile, sender=User)
所以,我卡在了这个阶段,无法前进。提前致谢。
您不必创建信号文件...就在 UserProfile
之后from django.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
....
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
要在创建用户后(通过 models.py)在用户配置文件 table 中创建一行,您可以从管理界面或 shell 或在前面创建一个表单-结束然后发布并保存它。 (我正在为您提供示例代码 - 其中的各种属性现在可能对您没有用。仅供您理解)。
shell 方法可以是这样的:
$ ./manage.py shell
>>> from django.contrib.auth import User
>>> from <package_profile>.models import UserProfile
>>> new_user = UserProfile(user_auth = new_user, name = name,...) # other whatever fields you want
>>> new_user.save()
表单方法可以是这样的:
from django.shortcuts import render
from django.http import HttpResponse
from <package_profile>.models import USerProfile, Developer
from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
@login_required
def page(request):
if request.POST:
form = Form_inscription(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
login = form.cleaned_data['login']
password = form.cleaned_data['password']
# User auth details:-
new_user = User.objects.create_user(username = login, password = password)
new_user.is_active = True
new_user.email = email
new_user.first_name = name
new_user.save()
new_developer = Developer(user_auth = new_user, name = name, email = email)
new_developer.save()
return HttpResponse("Developer added")
else:
return render(request, create_developer.html', {'form' : form})
else:
form = Form_inscription()
return render(request,create_developer.html', {'form' : form})
class Form_inscription(forms.Form):
name = forms.CharField(label="Name", max_length=30)
login = forms.CharField(label = "Login")
email = forms.EmailField(label = "Email")
password = forms.CharField(label = "Password", widget = forms.PasswordInput)
password_bis = forms.CharField(label = "Password Re-enter", widget = forms.PasswordInput)
def clean(self):
cleaned_data = super(Form_inscription, self).clean()
password = self.cleaned_data.get('password')
password_bis = self.cleaned_data.get('password_bis')
if password and password_bis and password != password_bis:
raise forms.ValidationError("Passwords are not identical.")
return self.cleaned_data
表格的对应 html 将是:
{% extends "base.html" %}
{% block title_html %}
Create Developer/User
{% endblock %}
{% block h1 %}
Create Developer
{% endblock %}
{% block article_content %}
<form method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<p><input type="submit" value="Create" /></p>
</form>
{% endblock %}