【发布时间】:2017-08-23 16:48:15
【问题描述】:
我正在尝试在 django 中扩展用户个人资料,以便用户可以添加个人资料照片和生日日期,并且我正在使用 django-allauth 进行用户身份验证。我目前正在关注参考,但作为参考,使用了新的用户注册,而不涉及 django-allauth。因此,我已经实现了代码,但在某个地方我无法弄清楚该特定代码行的放置位置
# Create the user profile
profile = Profile.objects.create(user=new_user)
下面是配置文件编辑代码 型号
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=True)
photo = models.ImageField(
upload_to= upload_location,
null = True,
blank = True,
height_field = "height_field",
width_field = "width_field")
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
Form.py
class UserEditForm(forms.ModelForm):
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email']
class ProfileEditForm(forms.ModelForm):
"""docstring for ProfileEditForm."""
class Meta:
model = Profile
fields = ['date_of_birth', 'photo']
查看
def edit(request):
if request.method == 'POST':
user_form = UserEditForm(instance = request.user, data = request.POST)
profile_form = ProfileEditForm(instance = request.user.profile, data = request.POST, files = request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
else:
user_form = UserEditForm(instance= request.user)
profile_form = ProfileEditForm(instance=request.user.profile)
return render(request, 'account/edit.html',
{'user_form': user_form, 'profile_form': profile_form})
如果我尝试运行这样的代码,则会收到错误User has no profile.,任何进一步的代码都将根据请求提供。
网址
url(r'^profile/edit/$', views.edit, name='update_profile'),
模板
<form method="POST" action="." class="" enctype="multipart/form-data"/>
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="submit" value="update">
</form>
【问题讨论】:
-
添加
urls.py和template。 -
您只需要为每个用户创建一个配置文件?对吧?创建新用户后,您可以使用信号为每个用户添加个人资料。
-
我已将其包含在@PiyushMaurya
-
@Navid2zp 我希望用户能够编辑他们的个人资料以上传照片,因为注册时没有上传照片
-
您是否注意为每个用户制作个人资料?唯一的问题是上传照片?或者您需要做所有事情,包括为每个用户创建一个配置文件,其中包括几个字段,如头像和...?
标签: python django django-allauth