I have an application that passes the user name from the HTML template to the URL and functions in the views.
views.py
def cv_detail_view(request, username):
if username=='':
return redirect("accounts:login")
else:
user = get_object_or_404(User, username=username)
try:
personal_info = PersonalInfo.objects.get(user=user)
except PersonalInfo.DoesNotExist:
# if personal info doesn't exist redirect to create or 404 page.
if user == request.user:
return redirect("cvs:create_personal_info")
else:
raise Http404("CV Does Not Exist.")
work_experience = WorkExperience.objects.filter(user=user)
education = Education.objects.filter(user=user)
context = {
"personal_info": personal_info,
"work_experience": work_experience,
"education": education,
}
return render(request, "detail.html", context)
Html snippet:
<li><a href="{% url 'cvs:cv_detail' username=request.user.username %}">Use templates</a></li>
ursl.py
path(r'^(?P<username>[\w._-] )/$',views.cv_detail_view,name='cv_detail'),
My idea is to redirect users to login page if the parameter username
is empty i.e, if the user is not logged in. However, I get the following error:
NoReverseMatch at /
Reverse for 'cv_detail' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['cvs/\\^\\(\\?P(?P<username>[^/] )\\[\\\\w\\._\\-\\]\\ \\)/\\$\\Z']
Request Method: GET
Request URL: http://127.0.0.1:9090/
Django Version: 4.0.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'cv_detail' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['cvs/\\^\\(\\?P(?P<username>[^/] )\\[\\\\w\\._\\-\\]\\ \\)/\\$\\Z']
Is there any way to handle the empty value in function arguments?
CodePudding user response:
Can you add in the template this:
{% if request.user.username %}
<li><a href="{% url 'cvs:cv_detail' username=request.user.username %}">Use templates</a></li>
{% endif %}