【问题标题】:extend a user profile in django to include profile photo在 django 中扩展用户个人资料以包含个人资料照片
【发布时间】: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.pytemplate
  • 您只需要为每个用户创建一个配置文件?对吧?创建新用户后,您可以使用信号为每个用户添加个人资料。
  • 我已将其包含在@PiyushMaurya
  • @Navid2zp 我希望用户能够编辑他们的个人资料以上传照片,因为注册时没有上传照片
  • 您是否注意为每个用户制作个人资料?唯一的问题是上传照片?或者您需要做所有事情,包括为每个用户创建一个配置文件,其中包括几个字段,如头像和...?

标签: python django django-allauth


【解决方案1】:

在你看来,添加(或在别处添加,然后导入):

def load_profile(user):
  try:
    return user.profile
  except:  # this is not great, but trying to keep it simple
    profile = Profile.objects.create(user=user)
    return profile

然后将您的视图函数更改为使用load_profile(request.user) 而不是request.user.profile

查看

def edit(request):
    profile = load_profile(request.user)
    if request.method == 'POST':
        user_form = UserEditForm(
            instance=request.user,
            data=request.POST,
        )
        profile_form = ProfileEditForm(
            instance=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=profile)

    return render(
        request,
        'account/edit.html',
        {'user_form': user_form, 'profile_form': profile_form}
    )

【讨论】:

  • 对不起,我很困惑
  • 您的问题是user 上没有profile 属性。此函数接受user 对象,并尝试返回profile。如果不存在(您看到的错误),则会引发 DoesNotExist 异常。该函数捕获该异常,然后创建一个新配置文件以附加到用户,并返回该新配置文件。
  • 好的。我理解您的解释,但您能否帮助编辑您的答案以包含我的观点?
  • 好的,但就像我说的那样,它实际上只是将 request.user.profile 替换为调用 load_profile(request.user) 的结果。
  • 我实际上已经这样做了,但现在的问题是它没有创建配置文件
【解决方案2】:

您的错误告诉用户配置文件不存在: 在你的view:

def edit(request):
    if request.method == 'POST':
        profile_form = ProfileEditForm(request.POST, request.FILES)

        if profile_form.is_valid():
            instance = profile_form.save(commit=False)
            instance.user = request.user
            instance.save()
            return # add here

    else:
        profile_form = ProfileEditForm()

    return render(request, 'account/edit.html', {'profile_form': profile_form})

它会起作用的。

【讨论】:

  • 我没有包含user_form,因为错误是由profile_form引起的。
  • 请把它包括在内,因为我没有看到任何有个人资料的地方
  • 使用它并检查照片是否正在更新/上传。
  • 表单未显示在模板上。它没有加载,但没有错误
  • template 中,仅使用{{ profile_form.as_p }} 然后检查。删除{{ user_form.as_p }}只是为了测试,一旦成功,你可以稍后添加。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 2021-07-24
相关资源
最近更新 更多