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 %}">
Related
I have a blog page with the path /articles/. I would like to use conditional statements to reflect HTML renders.
For example, my blog uses a paginator for blog posts. The paginator uses a URL query to retrieve the next page of post objects like so: /articles/?page=2
I would like for the next page to stylize the HTML template differently, hence my reasoning for using a conditional statement.
Here is my template that I use:
{% if request.path == '/articles/' %}
# Render HTML only meant for the above path
{% elif request.path != '/articles/'%}
# Render HTML for paths that are NOT the exact match above, such as pagination URLs,
# search querys, categories filtering, etc...
{% endif %}
My current bug is that I'm only rendering the first statement: if request.path == '/articles/' for everything, even non exact matches.
So this URL path: /articles/?page=2 is rendering: {% if request.path == '/articles/' %} when it should be rendering the elif {% elif request.path != '/articles/'%} due to the not equals sign.
Is the above possible to do with only HTML template tags? I know I can use urls.py and edit views but I'm using wagtail CMS and playing with the template seems like the most easiest thing to do right now.
request.path does not include the '?...' querystring part of the URL, so this is working as designed - the path portion of the URL /articles/?page=2 is /articles/.
Django compiles the querystring into the dictionary request.GET, so one way of doing what you want is to check whether that dictionary is empty or not:
{% if not request.GET %}
request is for the plain URL /articles/
{% else %}
request has a querystring parameter on it
{% endif %}
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 know that in a template file I can include this code which will return a list of links
{% for q in all %}
<ul>
<li><a href={% url 'detail' q.id %}>{{ q.question_text }}</a></li>
</ul>
{% endfor %}
Now django will search for the name 'detail' in the urls.py file of my app directory and it will automatically give the value of q.id to that argument. But what if I have a url that contains more than 1 variable. So here I can only give one argument i.e, q.id. But what if I want to give more than one argument.
Hope I am clear
Well you can see the urls.py as a declaration of how URLs map to view functions (and class-based views). A url can have an arbitrary number of parameters.
If we have for example the following URL:
url(r'^detail/(?P<year>(\d+))/(?P<name>(\w+))/$', views.detail),
We can see this url as some sort of virtual function that would take parameters like:
def some_url(year, name):
# ...
pass
So we can construct this URL with unnamed parameters:
{% url 'detail' 1981 q.name %}
or with named parameters:
{% url 'detail' name=q.name year=1981 %}
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 have a certain link to a url in a Django template. I would like to grab all the GET parameters of the current page url and add them to the url of the template's link. The current page might have zero GET parameters.
Include the django.core.context_processors.request context processor in your settings.py, then use the request object in your template's links:
<a href="{% url 'my_url' %}?{{ request.META.QUERY_STRING }}">
This will cause links from a page without any GET variables to have a trailing ? but that's harmless. If that's not acceptable, you could test for them first:
<a href="{% url 'my_url' %}{% if request.META.QUERY_STRING %}?{{ request.META.QUERY_STRING }}{% endif %}">
you could pass request.META['QUERY_STRING'] to the template.
You can grab the get params before you render the template and pass them to the template and render them on the correct link.
You could also build a query string from request.GET
The GET parameters of the current request are stored in HTTPRequest.Get.