Will someone please explain to me what on earth is going on in the Django tutorials when I see this?
{% url 'polls:detail' poll.id %}
It's outputting what exactly? The poll.id I understand, is that being passed as some sort of argument or is it appending to the url? How exactly does this work? Is it calling a url.py and iterating over those urls patterns?
The {% url ... %} template tag looks up a named URL in your views (url patterns) configuration, and produces a URL that would allow a browser to call that view.
The arguments following the URL id are filled into the url pattern; if the pattern is defined as:
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
The (?P<poll_id>\d+) group is the first 'argument' to the URL; the tag {% url 'polls:detail' poll.id %} takes this pattern and replaces the first group in it with the poll.id value.
Instead of positional arguments, you can also name each captured group explictly:
{% url 'polls:detail' poll_id=poll.id %}
would achieve the same result.
Because the tutorial included all of the polls urls under the polls/ url path with:
url(r'^polls/', include('polls.urls')),
the final URL generated uses the current hostname and port plus /polls/ followed by the poll id and another slash. If poll.id is 1, and you access your site with http://localhost:8000/ that all comes together as:
http://localhost:8000/polls/1/
The output will be :
/url/absolute/depending.on.urls.py
To use it with an "a" just do :
Poll {{ poll.id }}
Related
Whenever I click the button this error showup
I have no idea why is this happening.
error
NoReverseMatch at /admin-chat-list/
'admin-chat' is not a registered namespace
html file
<form mthod="POST" action="{% url 'admin-chat:{{data.email}}' %}">
<input type="submit" value="CHAT">
</form>
urls.py
path('admin-chat/<str:merchant_email>/', views.admin_chat, name='admin-chat'),
views.py
def admin_chat(request, merchant_email):
print(merchant_email)
if request.method == 'POST':
msg = request.POST['message']
Message.objects.create(sender=request.user,
receiver=merchant_email, message=msg)
return redirect('admin-chat')
return render(request, 'dashboard/admin/chat.html')
The format of your django url tag is incorrect.
You are not using a namespace in your urls.py file, but you are naming one in your url tag:
<form method="POST" action="{% url 'admin-chat:{{data.email}}' %}">
In a django url tag, the text before the colon ':' is used specifically (and only) to name a namespace. Your tag, as currently written, expects your urls.py file to look like this:
app_name = 'admin-chat'
url_patterns = [
path('admin-chat/<str:merchant_email>/', views.admin_chat, name='admin-chat'),
]
Since you are not using a namespace like above, you cannot reference a namespace in your url tag. I see that you've named your URL pattern 'admin-chat', so it seems you are simply confused about the proper syntax of the django url tag. When you put 'admin-chat' before : inside the tag, django does not read that as your named URL, it reads it as a namespace.
(Note: the above example code is meant only to show what your current tag is looking for in your urls.py; in actuality, you would never want to have a namespace that is identical to a named url, as seen above).
A django url tag has the format: {% url 'some-url-name' optional_arguments %}. Therefore, you can simply provide your named url pattern, admin-chat, in quotes, and after that, add the additional argument(s) you are passing to the url:
<form method="POST" action="{% url 'admin-chat' data.email %}">
This is the correct format for a django url tag with an (optional) argument included. Note that when adding the argument, you do not need to nest a django variable tag (double curly braces) inside a django template tag, as you've done in your original code.
I want a URL something like this:
/(category)/(post-slug)
On the link this is what I have:
{% url blog.category blog.slug %}
and for the url.py:
url(r'^(I DON"T KNOW WHAT TO PUT ON THIS PART TO GET THE CATEGORY)/(?P<slug>[0-9A-Za-z._%+-]+)', views.post, name='post'),
thanks
EDIT:
This is what I have now:
Still have NoReverseMatch error at /
urls.py
url(r'^(?P<category>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$', views.post, name='post'),
index.html
<a href="{% url blog.category blog.slug %}">
views.py
def post(request, slug, category):
try:
blog = Blog.objects.get(slug=slug)
except Blog.DoesNotExist:
raise Http404('This post does not exist')
return render(request, 'parts/post.html', {
'blog': blog,
})
Firstly, your URL tag needs the name of the pattern you are reversing as the first argument:
{% url 'post' blog.category blog.slug %}
or if you are using a namespace, something like:
{% url 'blog:post' blog.category blog.slug %}
You haven't shown your views or models, so we can only guess what your URL pattern should be. I'm not sure why you find the category confusing - you just need to choose a name for the group (e.g. category_slug), and the regex for the group (you might be able to use the same one as you use for slug). That would give you:
url(r'^(?P<category_slug>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$'
Note that there should be a dollar on the end of the regex.
I am facing 2 issues NoReverseMatch and APPEND_SLASH .
Issue #1. APPEND_SLASH
Detail.html
<form action="update-entry" method="post">
/* if I add '/' at the end of update-entry, it works fine. */
{% csrf_token %}
{{ form }}
<input type="submit" value="Edit">
</form>
When I click on the Edit button, I get the error below,
You called this URL via POST, but the URL doesn't end in a slash and you have
APPEND_SLASH set. Django can't redirect to the slash URL while maintaining
POST data. Change your form to point to 127.0.0.1:8000/genericviews/1/update-
entry/ (note the trailing slash), or set APPEND_SLASH=False in your Django
settings.
This is the URL generated:
http://127.0.0.1:8000/genericviews/1/update-entry
I know URL should end with '/'.
urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name='detail'),
url(r'^makeentry$', views.makeentry, name='makeentry'),
url(r'^static/$', views.StaticView.as_view()),
url(r'^new-entry/$', views.MakeEntryView.as_view(), name='new-entry'),
url(r'^(?P<pk>[0-9]+)/update-entry/$', views.UpdateEntryView.as_view(), name='update-entry'),
]
My confusion is why URL is not generating '/' at the end. Above URL pattern seems correct to me.
Issue #2 NoReverseMatch
When I try to change the hardcoded URL, I get the error below,
NoReverseMatch at /genericviews/1/
Reverse for 'update-entry' with arguments '()' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['genericviews/(?P<pk>[0-9]+)/update-
entry/$']
Detail.html
<form action="{% url 'genericviews:update-entry' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Delete Product">
</form>
tried link as well,
{#Edit#}
When I click on any item from the page http://127.0.0.1:8000/genericviews/,
it takes me to the URL http://127.0.0.1:8000/genericviews/1/
And this is where it shows error.
I checked other answers, however, couldn't get it to work.
Any help would be appreciated.
It's not adding a slash because you haven't asked it to. You've hard-coded the relative URL of "update-entry", so that's what it will use.
When you do try and use the url tag, you get the error because you haven't passed the arguments it needs to generate that URL. Assuming you have the object in your template context as object, you would do:
{% url 'genericviews:update-entry' pk=object.pk %}
in views.py
class LaViewSet(viewsets.ModelViewSet):
serializer_class = IlSerializer
def get_queryset(self):
ilfiltro = self.kwargs['miopar']
return models.Pippo.objects.filter(pippo=ilfiltro)
in url.py
url(r'^pippo/(?P<miopar>.+)', views.LaViewSet.as_view({'get': 'list'}), name="Serializzata"),
this is a working url:
http://127.0.0.1:8000/pippo/1
but if I put in a template:
{% url '1' 'Serializzata' %};
or
{% url 'Serializzata'?1 %};
keep getting this error:
TemplateSyntaxError: Could not parse the remainder: '?1' from
''Serializzata'?1'
From the docs:
url
Returns an absolute path reference (a URL without the domain name)
matching a given view and optional parameters. Any special characters
in the resulting path will be encoded using iri_to_uri().
This is a way to output links without violating the DRY principle by
having to hard-code URLs in your templates:
{% url 'some-url-name' v1 v2 %}
So in your case:
{% url 'Serializzata' 1 %}
Try this:
<a href="{% url 'Serializzata' 1 %}">
So I am working on a website where at some point I do a search and list a list of textbooks on the page. From there I want the user to be able to click on a textbook and each textbook will have it's own details page. I have been trying to work with Django's URL dispatcher but I am having difficulties. Code and description below.
results.html
<table class="table">
{% for items in results %}
<tr><td>{{items.textbook_name}}</td><td>{{items.class_name}}</td><td>{{items.author}}</td><td>{{items.isbn}}</td><td>></td></tr>
{% endfor %}
</table>
Views.py
def textbook(request, text_name):
return render_to_response(
'textchange/textbook.html',
locals(),
context_instance=RequestContext(request)
)
Urls.py
url(r'^results/(?P<text_name>\w+)/$', views.textbook, name="textbook"),
From my understanding I thought I was passing the items.textbook_name as text_name to urls from the html and then views would be called with text_name as an argument but it is not working. I might be a little backwards here. I need the textbook_name from the textbook the user clicks on so on the details page I can display all it's information from the database.
Thanks.
Quick explanation.
Let's say that your url doesn't need text_name parameter, so that:
{% url 'textchange:textbook' %}?text_name={{items.textbook_name}}
will result in:
/results/?text_name=some-name
text_name won't get passed to url tag, it was simply glued on the end of url.
To pass text_name into url, and build proper url, you should do that:
{% url 'textchange:textbook' text_name=items.textbook_name %}
and it will result in url:
/results/some-name/