如何解决此错误:
int() argument must be a string, a bytes-like object or a number, not 'User'
我想创建我不愿意修复的用户个人资料!
我要在注册时创建用户页面,但我一次又一次收到此错误
Base.Html
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'profile' pk=user.pk %}"><i class="fa fa-user"></i> Profile</a>
</li>
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'logout' %}"><i class="fa fa-power-off"></i> Logout</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'register' %}"><i class="fa fa-check-square-o"></i> Sign up Free</a>
</li>
<li class="nav-item">
<a class="nav-link navaour" href="{% url 'login' %}"><i class="fa fa-user"></i> Login</a>
</li>
{% endif %}
Urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.index,name='index'),
path('accounts/signup/', views.user_reg,name='register'),
path('profile/<int:pk>',views.profile_detail,name='profile')
]
Views.py
def profile_detail(request,pk):
pk = User.objects.get(pk=pk)
model = get_object_or_404(User, pk=pk)
template_name = 'profile_detail_view.html'
这是我的 Models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class user_register_model(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse("profile",kwargs={'pk':self.pk})
错误:
任何帮助得到赞赏 谢谢!
答案 0 :(得分:1)
def profile_detail(request,pk):
pk = User.objects.get(pk=pk)
model = get_object_or_404(User, pk=pk)
template_name = 'profile_detail_view.html'
尝试删除以下行:
pk = User.objects.get(pk=pk)
答案 1 :(得分:0)
在配置文件路径中,您要将用户ID作为参数传递给url:
path('profile /',views.profile_detail,name ='profile')
但是您将用户模型(而不是模板中的id)传递给它:
<a class="nav-link navaour" href="{% url 'profile' pk=user.pk %}"><i class="fa fa-user"></i> Profile</a>
应该是这样的:
<a class="nav-link navaour" href="{% url 'profile' pk=user.id %}"><i class="fa fa-user"></i> Profile</a>
并且您需要修复以将pk字符串转换为int以进行查询的视图:
def profile_detail(request,pk):
model = get_object_or_404(User, pk=int(pk))
template_name = 'profile_detail_view.html'
答案 2 :(得分:0)
class user_register_model(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
def __str__(self):
return str(self.user.username)
def get_absolute_url(self):
return reverse("profile",kwargs={'pk':self.pk})
向模型添加 str 功能
答案 3 :(得分:0)
我猜这在您的views.py
代码User.objects.get(pk=pk)
中是一个问题,返回了User对象。因此您的代码必须是
user=User.objects.get(pk=pk)
model = get_object_or_404(User, pk=user.pk)