我在防止编辑其他用户的个人资料方面遇到麻烦,而且我不知道如何解决此问题。
当然,我知道我可以做这样的事情:
<a class="nav-item nav-link" href="{% url 'profile_change' user.pk %}">
或类似的东西。
但是我不知道当用户编写他/她自己的网络地址时我能做些什么。我的意思是,当pk = 2的用户会写地址:“网站地址/配置文件/更改/ 1”
这是我的模型,视图和网址:
#urls.py
urlpatterns = [
path('profile/', views.profile, name='profile'),
path('profile/list/', views.ProfileListView.as_view(), name='profile_changelist'),
path('profile/add/', views.ProfileCreateView.as_view(), name='profile_add'),
path('profile/change/<int:pk>/', views.ProfileUpdateView.as_view(), name='profile_change')
]
#views.py
class ProfileCreateView(CreateView):
model = Profile
form_class = ProfileForm
success_url = reverse_lazy('profile_changelist')
def form_valid(self, form, **kwargs):
form.instance.user = self.request.user
return super().form_valid(form)
class ProfileUpdateView(UpdateView):
model = Profile
fields = ('first_name', 'last_name', 'year')
success_url = reverse_lazy('profile_changelist')
@login_required
def profile(request):
if Profile.objects.filter(user=request.user.id).count() == 1:
return render(request, 'profiles/profile.html')
else:
return HttpResponseRedirect('add')
#models.py
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=100, null=True)
last_name = models.CharField(max_length=100, null=True)
year = models.IntegerField(choices=YEARS, default=1)
答案 0 :(得分:0)
您必须根据参数检查请求对象中的用户是可编辑用户:
from django.http import Http404
class ProfileUpdateView(UpdateView):
model = Profile
fields = ('first_name', 'last_name', 'year')
success_url = reverse_lazy('profile_changelist')
def get(self, request, *args, **kwargs):
if not request.user.id == self.kwargs.get('pk'):
raise Http404
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
if not request.user.id == self.kwargs.get('pk'):
raise Http404
return super().post(request, *args, **kwargs)