【发布时间】:2020-01-22 14:16:18
【问题描述】:
我的问题有两个,都围绕 NoReverseMatch 错误。 第一个问题:每次在使用不同视图的其他页面中调用我的 url({% url 'dashboard' client.pk %}) 时,我都会收到 NoReverseMatch 错误(例如DashboardPilot:请检查网址)但是当我在dashboard.html中使用它时,它工作正常。
Views.py
>class Dashboard(LoginRequiredMixin, UserPassesTestMixin, DetailView):
model = ClientProfile
template_name ='accounts/dashboard.html'
context_object_name= 'client'
login_url= 'login'
fields = '__all__'
def test_func(self):
return self.request.user.role == 'client'
urls.py
urlpatterns =[
path('accounts/dashboard/client/<int:pk>', Dashboard.as_view(), name='dashboard'),
path('accounts/dashboard/pilot/<int:pk>', DashboardPilot.as_view(), name='pilot_dashboard'),
path('jobs', JobPage.as_view(), name='job_page'),
path('job/<int:pk>/details', JobDetails.as_view(), name='job_details'),
path('accounts/edit/job/<int:pk>', EditJob.as_view(), name='job_edit'),
]
**models.py**
class ClientProfile(models.Model):
username = models.ForeignKey(User, on_delete= models.CASCADE)
client_firstname=models.CharField(max_length=200)
client_lastname=models.CharField(max_length =150)
role =models.CharField(max_length =150)
client_phone_no=models.CharField(max_length =150)
client_email=models.EmailField(max_length=150)
第二个问题: 我有一个视图在签名后重定向到仪表板(使用 pk),但每次尝试重定向到仪表板时我都会收到反向错误。
views.py
def signin (request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request,user)
messages.success(request, 'You are now logged in')
if user.role == 'client':
return redirect ('dashboard')
else:
return redirect ('pilot_dashboard')
else:
messages.error(request, 'Invalid Credentials')
return redirect ('login')
else:
return render (request, 'accounts/signin.html')
urls.py
urlpatterns =[
path('accounts/dashboard/client/<int:pk>', Dashboard.as_view(), name='dashboard'),
path('accounts/dashboard/pilot/<int:pk>', DashboardPilot.as_view(), name='pilot_dashboard'),
path('jobs', JobPage.as_view(), name='job_page'),
path('job/<int:pk>/details', JobDetails.as_view(), name='job_details'),
path('accounts/edit/job/<int:pk>', EditJob.as_view(), name='job_edit'),
]
我尝试过使用 return redirect(reverse('dashboard', args=[str(self.id)])),但我一直没有定义自我。 我将非常感谢您提供的任何帮助。
【问题讨论】:
标签: django python-3.x django-templates django-views django-urls