我想允许用户仅编辑他们的个人资料。这是我的网址:
url(r'^profile/(?P<pk>[0-9]+)/$', views.UserUpdate.as_view(), name='profile')
现在,当用户点击我的个人资料&#39;他们将获得他们可以编辑的自己的个人资料,但如果他们在浏览器中手动编辑urlpath并输入其他用户的ID,则可以查看和编辑其他用户的个人资料
http://127.0.0.1:8000/profile/1/
这是我的观点
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')
现在在user_form.html我已检查用户是否经过身份验证,以便只有登录用户才能查看个人资料页面但仍然登录用户可以查看其他用户的个人资料。
{% 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>
这是我的模特:
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()
如何限制登录用户仅编辑其个人资料?我知道有很多类似的问题和堆栈溢出可能重复,但似乎没有一个帮助我的情况。
提前致谢
答案 0 :(得分:1)
您可以像这样删除网址中的pk
url(r'^profile/$', views.UserUpdate.as_view(), name='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
通过这种方式,您可以确保个人资料视图仅使用用户自己的个人资料加载。
另外,您可能希望将视图限制为仅允许登录用户。