View answers in my template translate t...">

Django: href problem {% url%}

Why

<a href="{% url 'answers.views.display_answers' Question.id %}">View answers</a> 

in my template translate to this interpretation of Django:

 Request URL: http://127.0.0.1:8000/questions/%7B%%20url%20'answers.views.display_answers'%20Question.id 

which of course leads to a URL mismatch error.

Looks like reading in my '{' in ASCII form. Can anyone enlighten me why this is so?

EDIT:

This is how I displayed the template -

 return render(request, 'display_questions.html', context) 

and the template contains href. My on-screen answer shows a redirect to another view as such:

 def display_answers(request, q_id): q = get_object_or_404(Question, id=q_id) ans_list = Answer.objects.filter(question=q) context = {'question': q, 'ans_list': ans_list} return redirect('view_answers.html', context) 

Error:

The current URL, questions / {% url 'answers.views.display_answers' Question.id, do not match any of them.

+4
source share
3 answers

It is right. If not, your urls.py seems wrong. Please post it.

 <a href="{% url answers.views.display_answers question.id %}">View answers</a> 

Edit Here is the best version of your presentation.

 from django.template import RequestContext from django.core.urlresolvers import reverse from django.shortcuts import render_to_response, redirect, get_object_or_404 def display_answers(request, q_id): q = get_object_or_404(Question, id=q_id) ans_list = Answer.objects.filter(question=q) context = {'question': q, 'ans_list': ans_list} return render_to_response('view_answers.html', context, RequestContext(request)) 
+2
source

The problem is your use of redirect in the view. You should use render or render_to_response if you really don't want to redirect the browser. (Pay attention to the developer tools of Fiddler, Firebug or Chrome, and you will see that it is being redirected.)

The reason this is not so obvious is because redirect can accept the URL as its first argument. 'view_answers.html' interpreted as a relative URL that may or may not appear in the URL of your URLconf. If it displays the URL, you get a false positive that everything works, but if your web server processes this link instead of Django, it can just send the template page in plain text. The solution, as I said, is either render , or render_to_response to render the page, or redirect with the name of the view or the special name of the URL pattern to redirect to another view.

0
source

Change your redirects in your display_answers view to use the view name instead of your template name ( view_answers.html ) and not pass context to it ( redirect does not accept context as a parameter):

 return redirect('your_view_answers_view') 
0
source

Source: https://habr.com/ru/post/1439447/


All Articles