Django:django.urls.exceptions.NoReverseMatch:找不到参数为'(',)'的'update'的反向

时间:2019-11-08 16:38:00

标签: django django-templates

登录后尝试渲染模板时,我会得到

  

django.urls.exceptions.NoReverseMatch:反向使用“ update”   找不到关键字参数'{'pk':''}'。尝试了1种模式:   ['users /(?P [0-9] +)/ update / $']

我在urls.py中的一行:

library('tidyverse')

chessboard = function(n){
  if(n > 26){
    stop('Ya board too big!')
  }
  board = expand_grid(X = 1:n, Y = 1:n)
  board = board %>% 
    mutate(color = ifelse((X - Y) %% 2 == 0, 'black', 'white')) %>% 
    mutate_all(factor)
  letter_labs = LETTERS[1:n]


  ggplot(data = board, aes(x = X, y = Y, fill = color)) +
    geom_tile() +
    scale_fill_manual(values = c('black' = "#FFFFFF", 'white' = "#000000")) +
    scale_x_discrete(labels = letter_labs, name = '') +
    scale_y_discrete(labels = letter_labs, name = '') +
    theme(legend.position = 'none')

}
chessboard(10)

然后在模板中插入行:

app_name="users"
...

path("users/<int:pk>/update/", view=user_update_view, name="update"),

我看到 request.user.pk 没有提供价值,但我不知道为什么。

1 个答案:

答案 0 :(得分:1)

为防止这种情况在用户未登录时写入

{% if request.user.is_authenticated %}
<a href="{% url 'users:update' %}">Update user</a>
{% else %}
 <p> user not logged in </p> or whatever you want!!
{% endif %}

我认为通过在url参数中传递id更新当前登录的用户不是一个好主意。如果有人故意在地址栏中键入其他ID,则他/她可以更新任何人的个人资料。因此,不要像下面这样更改您的网址。 path("users/update/", view=user_update_view, name="update"),,并在您看来

@login_required
def user_update_view(request):
    user= User.objects.get(id=request.user.id)

    # whatever you want!!