Two variables in Django URL - python

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.

Related

passing django variables as parameters into href url

On my home page i want to have 3 links that will redirect the user to a page ('127.0.0.1:8000/person/<str:name>') which will display the name that they clicked. I would like to use a for loop to create links for these names as i plan to have much more than 3 names.
I have tested with the two methods (for loop / manually writing out all of the links) but can't get the for loop to work.
I thought these two methods below would produce the same result.
<h2>does not work</h2>
{% for person in people %}
{{person}}
{% endfor %}
<h2>works</h2>
logan
paul
nicola
What the urls look like in page source:
views.py
def home(request):
return render(request, "APP/home.html", context={"people":['logan', 'paul', 'nicola']})
def person(request, name):
return render(request, 'APP/person.html', context={"name":name})
urls.py
urlpatterns = [
path('home/', views.home, name='home'),
path('person/<str:name>/', views.person, name='person'),
]
You don't need to wrap person variable into {{}} signs since in url tag you should use it directly:
{% for person in people %}
{{person}}
{% endfor %}
Check example here.

how to make sub pages url in django

In my online store django project, I want to create a sub-page which shows the details of a product that is listed in a page.
in urls.py I created the urls for both pages like bellow:
path('wwqm', views.water_quality_sensor , name='wwqm'),
path('wwqm/<str:water_sensor_title>', views.water_sensor_item, name='water_sensor_item'),
in this scenario, a bunch of items are being shown in wwqm. user click on a product and the water_sensor_item should load up.
I know its not important but here is views.py:
def water_quality_sensor(request):
queryset_list = Water_quality_sensor.objects.order_by('-product_name').filter(is_published=True)
context = {
'water_quality_sensor': queryset_list,
}
return render(request, 'products/water_quality_sensor.html', context)
def water_sensor_item(request, water_sensor_title):
water_sensors = get_object_or_404(Water_quality_sensor, title=water_sensor_title)
context = {
'water_sensors': water_sensors
}
return render(request, 'products/water_sensor_item.html' , context)
I try to build the url for each item based on a parameter that is passed to its view(products title).
In my templates, I try to create a link like the following:
<a href="{% url 'water_sensor_item' w_q_sensor.title %}" class="card hoverable mb-4 text-dark" >
one my products' title is 3725. when I click on that product in the main page, I get the following error:
Django Version: 3.1.2
Exception Type: NoReverseMatch
Exception Value: Reverse for 'water_quality_sensor' not found. 'water_quality_sensor' is not a valid view function or pattern name.
What am I doing wrong?
in your urls.py
path('wwqm', views.water_quality_sensor , name='wwqm'),
you used name wwqm. But it looks like somewhere in your template (most likely water_sensor_item.html), you have something similar to :
<a href="{% url 'water_quality_sensor' %}"
Change it to wwqm or change name in urls.py
UPDATE
It is better to use <str:title><int:pk> in your urls, to avoid when you have the same name in two products. pk is unique.
in your urls.py
path('wwqm/<str:water_sensor_title><int:pk>', views.water_sensor_item, name='water_sensor_item'), # add <int:pk>
in your template:
# since url is taking both title and pk arguments, you need to provide both of them.
<a href="{% url 'water_sensor_item' title= w_q_sensor.title pk=w_q_sensor.pk %}" class="card hoverable mb-4 text-dark" >
in your view:
def water_sensor_item(request, water_sensor_title, pk): # added pk
water_sensors = get_object_or_404(Water_quality_sensor, pk=pk) # use pk to get the object
context = {
'water_sensors': water_sensors
}
return render(request, 'products/water_sensor_item.html' , context)

django url in template correct way to add parameter

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 %}">

Django - Passing parameters from template to view not working

I'm trying to get my hands dirty with django and I started trying to make my own project. I'm currently having trouble passing parameters from my template to my views without using POST requests.
heres my code in the template
#in main.html
<div>
{{ event_results }}
{{ friends }}
</div>
{% for user in results %}
<div class="userblock">
<p class="user">{{ user.username }}</p>
<a href="/events/addFriend/{{user.username}}">
<button class="navbuttons" id="addfriend">Add as friend</button>
<a/>
</div>
{% endfor %}
#in urls.py
from django.conf.urls import patterns, url
from events import views, eventview
url(r'^addFriend/(<requested_friend>[a-z]*)/', views.addFriend, name='addFriend'),
)
#in views.py
def addFriend(request, requested_friend):
currentUser = User.objects.get(username=request.session['username'])
try:
list_of_friends = Friends.objects.get(username=currentUser)
except (KeyError, Friends.DoesNotExist):
return render(request, 'events/main.html', {'friends': requested_friend})
else:
return render(request, 'events/main.html', {'friends':list_of_friends})
So when I click on the button "Add friend" in main.html, it goes to the url.py and maps it to the function addFriend in views.py with the argument and from there it does its magic. However, it's not taking in the argument. I know I'm doing something wrong in the urls.py with the regex but im not sure what. Any advice is greatly appreciated. Thanks!
When you change (<requested_friend>[a-z]*) to (?P<requested_friend>[0-9A-Za-z_\-]+) than everything looks fine.
But remember to use + instead of * in the pattern. * matches also a empty string (addFriend// is matched) but with + the string must have at least one character (addFriend// isn't matched)
You can add $ on the end of url pattern r'^addFriend/(?P<requested_friend>[0-9A-Za-z_\-]+)/$' Here you can find why.
Also check if link in browser has correct value /events/addFriend/<user_name>/ maybe is something wrong with {{ user.username }}
You have error in urls.py. In named group pattern you miss ?P prefix. See doc for reference.
Instead of
url(r'^addFriend/(<requested_friend>[a-z]*)/', views.addFriend, name='addFriend'),
It should be:
url(r'^addFriend/(?P<requested_friend>[a-z]*)/', views.addFriend, name='addFriend'),

How does the url work in Django <a> links?

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 }}

Categories

Resources