Django---允许用户只编辑他们的个人资料 [英] Django--- Allowing Users to only edit their profile

查看:21
本文介绍了Django---允许用户只编辑他们的个人资料的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想只允许用户编辑他们的个人资料.这是我的网址:

url(r'^profile/(?P<pk>[0-9]+)/$', views.UserUpdate.as_view(), name='profile')

现在,当用户点击我的个人资料"时,他们将获得自己的个人资料,他们可以编辑,但如果他们在浏览器中手动编辑 urlpath 并输入其他用户的 ID,如下所示,他们可以查看和编辑其他用户的个人资料

http://127.0.0.1:8000/profile/1/

这是我的看法

class UserUpdate(UpdateView):模型 = 简介fields = ['personal_info','job_title','department','location','expertise','user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']模板名称 = 'user_form.html'success_url = reverse_lazy('index')

现在在 user_form.html 中,我检查了用户是否经过身份验证,以便只有登录的用户才能查看个人资料页面,但仍然登录的用户可以查看其他用户的个人资料.

{% if user.is_authenticated %}<h3>{{ user.first_name }} 的个人资料</h3><form class="form-horizo​​ntal" action="" method="post" enctype="multipart/form-data">{% csrf_token %}{% 包含 'form-template.html' %}<div class="form-group"><div class="col-sm-offset-2 col-sm-10"><button type = "submit" class="btn btn-success">提交</button><a href={% url 'index' %}><input type="button" class=" col-sm-offset-2 btn btn-warning " name="cancel" value="Cancel"/>;</a>

</表单>

这是我的模型:

class Profile(models.Model):用户 = 模型.OneToOneField(用户,on_delete=models.CASCADE)Personal_info = models.TextField(blank=True)job_title = models.CharField(max_length=100, blank=True)部门=models.CharField(max_length=100,空白=真)location = models.CharField(max_length=100, blank=True)专业知识 = models.TextField(blank=True)phone_regex = RegexValidator(regex=r'^+?1?d{5,15}$', message="电话号码必须按以下格式输入:'+123456'.允许 5 到 15 位数字.")phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=True)contact_skype = models.URLField(空=真,空白=真)contact_facebook = models.URLField(空=真,空白=真)contact_linkedin = models.URLField(空=真,空白=真)user_photo = models.ImageField(upload_to='../media/img', blank=True)@receiver(post_save,sender=User)def create_user_profile(sender, instance, created, **kwargs):如果创建:Profile.objects.create(用户=实例)实例.profile.save()@receiver(post_save,sender=User)def save_user_profile(sender, instance, **kwargs):实例.profile.save()

如何限制登录用户只能编辑他们的个人资料?我知道在堆栈溢出中有很多类似的问题和可能的重复问题,但似乎没有一个对我的情况有帮助.

提前致谢

解决方案

你可以像这样从你的 url 中删除 pk

url(r'^profile/$', views.UserUpdate.as_view(), name='profile')

然后只获取用户的个人资料

class UserUpdate(UpdateView):模型 = 简介fields = ['personal_info','job_title','department','location','expertise','user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']模板名称 = 'user_form.html'success_url = reverse_lazy('index')def get_object(self):返回 self.request.user.profile

这样可以确保配置文件视图只加载用户自己的配置文件.

另外,您可能希望将视图限制为仅允许登录用户.

I want to allow User to only edit their profile. This is my URL:

url(r'^profile/(?P<pk>[0-9]+)/$', views.UserUpdate.as_view(), name='profile')

Now when the user click on 'my profile' they will get their own profile which they can edit but if they manually edit the urlpath in browser and enter other user's id like below, they can view and edit other User's profile

http://127.0.0.1:8000/profile/1/

this is my view

class UserUpdate(UpdateView):
model = Profile
fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']
template_name = 'user_form.html'
success_url = reverse_lazy('index')

Now in user_form.html I have checked if the user is authenticated so that only logged in user can view the profile page but still logged in User can view other user's profile.

{% if user.is_authenticated %}
                    <h3> {{ user.first_name }}'s Profile</h3>
                    <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                    {% csrf_token %}
                    {% include 'form-template.html' %}
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type = "submit" class="btn btn-success">Submit</button>
                            <a href={%  url 'index' %}><input type="button" class = " col-sm-offset-2 btn btn-warning " name="cancel" value="Cancel" /></a>
                        </div>
                    </div>
                    </form>

This is my model:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
personal_info = models.TextField(blank=True)
job_title = models.CharField(max_length=100, blank=True)
department = models.CharField(max_length=100, blank=True)
location = models.CharField(max_length=100, blank=True)
expertise = models.TextField(blank=True)
phone_regex = RegexValidator(regex=r'^+?1?d{5,15}$', message="Phone number must be entered in the format: '+123456'. Between 5 and 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=True)
contact_skype = models.URLField(null=True, blank=True)
contact_facebook = models.URLField(null=True, blank=True)
contact_linkedin = models.URLField(null=True, blank=True)
user_photo = models.ImageField(upload_to='../media/img', blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

How can I restrict logged in user to only edit their profile? I know there are lot of similar questions and possible duplicate in stack overflow but none seemed to help my case.

Thanks in advance

解决方案

You can just remove the pk from your url like so

url(r'^profile/$', views.UserUpdate.as_view(), name='profile')

And then only fetch the user's profile

class UserUpdate(UpdateView):
    model = Profile
    fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype']
    template_name = 'user_form.html'
    success_url = reverse_lazy('index')

    def get_object(self):
        return self.request.user.profile

That way you ensure, that the profile view is only ever loaded with the user's own profile.

On an additional note, you then might want to restrict the view to only allow logged in users.

这篇关于Django---允许用户只编辑他们的个人资料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆