Maybe this question has been answered before in one way or another. But I need to ask because I tried to answer it myself I googled it for days but I couldn't figure it out.
I have an app called reception in my Django project.
I figured out everything but this.
I have the link in the html directing to the right urlpattern.
<p><tab1>Reception</tab1></p>
urlpatterns = [..., path('go_to_reception', views.reception, name='go_to_reception'), ...]
And the view is like this
def reception(request):
return render(request, 'reception.html')
now instead of reception.html I want the link to go the reception page. The app page. What do I need to write there. I have tried everything that came to my mind but nothing worked.
the reception is as follows:
http://127.0.0.1:8000/admin/reception/
So how do I point to this.
Please help!
Thanks
So im just going to write the solution that we discussed in the chat:
{% url "admin:app_list" app_label="reception" %}
documentation
Look, this help you? i solve a similar problem in this way
url.py
path('gotoreception', views.reception, name="go_to_reception"),
html
<a href="{% url 'go_to_reception' slug=slug %}"
model
slug = models.SlugField(max_length=255, unique=True)
view
def home(request, slug):
context = {'yourdata':yourdata}
return render(request,'index.html', context)
On the template tag url you need use the name of your path, you can use a slug if you store the field on your db
3ยบ option but not recommended, you can add the value if you have on a variable but is not a good practice
I recommend you this 2 resources:
https://docs.djangoproject.com/en/2.1/ref/utils/
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/
hardcoded way
can you test this?
urls
urlpatterns = [..., path('reception/', views.reception, name='go_to_reception'), ...]
html
and on the link <a href="127.0.0.1/reception/">
is the hardcoded way but in the future you can have troubles or relative urls, 404 on internal pages
Thank you for your answer Matthew,
After your latest comment, I have changed my code to the following:
<p><tab1>Reception</tab1></p>
and in url.py its:
path('reception/', include('reception.urls', namespace='reception-urls')),
in reception.urls.py
app_name = "reception"
and the message now says:
django.urls.exceptions.NoReverseMatch: Reverse for 'go_to_reception' not found. 'go_to_reception' is not a valid view function or pattern name.
I am sorry for going back and forth like this, but I honestly can't make it work.
have you got a view called go_to_rececption in your reception.views or a url named go_to_reception in your reception.urls?.
and no worries just trying to help!!!
Related
There are few questions based on this idea like:
Implementing Ajax requests / response with django-allauth
Log in / Sign up directly on home page
https://www.reddit.com/r/django/comments/30lz11/django_allauth_implement_loginsignup_on_homepage/
but I need a little more help. I understand that I have to make form action url of modal as {% url 'account_login' %}. I have included {% load account %} and changed the 'name' and 'id' of username and password fields. My question is what other things I need to do to achieve this as it is still not working.
I had the same question and I wrote little tutorial for 3 methods I found so far. You can find details at https://stackoverflow.com/a/39235634/4992248
P.S. If it was just one method, I would post it here, but because I do not know which one you would prefer, I simply give you a link.
Novice here who learned to develop a web app with python using Flask. Now I'm trying to learn django 1.9 by redoing the same app with django.
Right now I am stuck at trying to get the current URL and pass it as an argument so that the user can come back once the action on the next page is completed.
In Flask, to return to a previous URL, I would use the 'next' parameter and the request.url to get the current url before changing page.
In the template you would find something like this:
Buy punchcard :
and in the view:
redirect(request.args.get("next"))
I thought it would be about the same with django, but I cannot make it work. I did find some suggestions, but they are for older django version(older than 1.5) and do not work anymore(and they are pretty convulsed as solutions goes!)
Right now, in my view I am using
return redirect(next)
Note: The use of return redirect in django seems very recent itself if I judge by solutions on the web that always seem to use return HttpResponse(..., so I take it alot of changes happened lately in how to do things.
and in the template I have
<a href="{% url 'main:buy_punchcard' member.id next={{ request.path }} %}">Buy punchcard</p>
but this actually return an error
Could not parse the remainder: '{{' from '{{'
I did add the context_processors in settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
But this is only the last error in a very long streak of errors. Bottom line is, I can't make it work.
As such, anyone could point me in the right direction as to what is the way to do this in django 1.9? It look like a pretty basic function so I thought it would be easier somehow.
If you want next to be included in the query string, then move it outside of the url tag:
<a href="{% url 'main:buy_punchcard' member.id %}?next={{ request.path }}">Buy punchcard</p>
In your view, you can fetch next from request.GET, and return the redirect response using either HttpResponseRedirect or the redirect shortcut.
from django.utils.http import is_safe_url
next = request.GET.get('next', '/default/url/')
# check that next is safe
if not is_safe_url(next):
next = '/default/url/'
return redirect(next)
Note that it might not be safe to redirect to a url fetched from the query string. For example, it could link to a different domain. Django has a method is_safe_url that it uses to check next urls when logging in or out.
You don't need {{ }} there, just:
<a href="{% url 'main:buy_punchcard' member.id next=request.path %}">Buy punchcard</p>
I'm following a few of the basic django blog tutorials. The part I am stuck on is how to set variables in my urls.
I want my urls to look like:
posts/1
posts/2
posts/3
Currently when i visit my index.html i see the list of blog posts (just the titles), and when I hover the cursor over each link it does show posts/1, posts/2, etc.
The problem is that when I click on these links, it basically just refreshes the page and does not show the detailed view.
my urls.py currently looks like this:
url(r'^posts/', index),
url(r'^posts/(?P<post_id>[0-9]+)/$', detailedview),
I'm not sure exactly what (?P[0-9]+)/$', does and I'm assuming this is the problem because detailedview is never being called.
This method is inside my views.py but again, it is never being called.
def detailedview(request, post_id):
targetpost = Post.objects.get(id="post_id")
context = {'targetpost': targetpost}
return render(request, 'posts/detailedview.html', context)
Your question about the second URL:
(?P<post_id>[0-9]+) is a regex that means "set the post_id argument to the value of any number with one or more digits (more info at https://docs.python.org/2/library/re.html.)
The way to fix your problem is to add a $ to the end of the first pattern, so it looks like this:
url(r'^posts/$', index),
This will make it only match the URL /posts/.
There is also a problem with your view: the line
targetpost = Post.objects.get(id="post_id")
should be:
targetpost = Post.objects.get(id=post_id)
This will make Django look for the Post with the id specified in the variable post_id, rather than the Post with the id that equals the string "post_id"
I have a situation which I hope you can help me. I have read a few post and answers about getting current url path on SO current_url and url TEMPLATE_CONTEXT_PROCESSORS (which are most relevant). But it doesn't seem to fit what I am trying to do. I have a view:
def fish_search(request):
args = {}
#irrelevant code here
args['fishes'] = fishes
args['current_path'] = request.get_full_path()
return render_to_response('ajax_search.html', args)
In my ajax_search.html:
<a id="search-results" href="{{ current_path }}"></a>
And base.html:
div id="search-results" ></div>
Javascript dumps the search results to base.html. And base.html is extended in fishMarket.html, fishDictionary.html, fishRumour.html, etc. So, sadly, the paths that show up are all "/search/"
I want the path to be /fishMarket/ if I am searching from fishMarket.html, /fishDictionary/ should show up if I am searching from fishDictionary.html, and likewise, /fishRumour/ if I am searching from fishRumour.html. Have anyone come across this type of situation? How did you solve this problem? I'm relatively new to django, so please dumb down the solution.
I really appreciate your help. many thanks!
Instead of using request.get_full_path(), which will give you path of search view, use referrer from the HTTP headers.
You can get that with request.META['HTTP_REFERER']
I'm having some trouble with the django generic object_list function's pagination not really being "smart" enough to compensate my daftness.
I'm trying to do a url for listing with optional arguments for page number and category.
The url in urls.py looks like this:
url(r'^all/(?:(?P<category>[-\w]+)/page-(?P<urlpage>\d+))?/$',
views.listing,
),
The category and urlpage arguments are optional beacuse of the extra "(?: )?" around them and that works nicely.
views.listing is a wrapper function looking like this( i don't think this is where my problem occurs):
def listing(request,category="a-z",urlpage="1"):
extra_context_dict={}
if category=="a-z":
catqueryset=models.UserProfile.objects.all().order_by('user__username')
elif category=="z-a":
catqueryset=models.UserProfile.objects.all().order_by(-'user__username')
else:
extra_context_dict['error_message']='Unfortunately a sorting error occurred, content is listed in alphabetical order'
catqueryset=models.UserProfile.objects.all().order_by('user__username')
return object_list(
request,
queryset=catqueryset,
template_name='userlist.html',
page=urlpage,
paginate_by=10,
extra_context=extra_context_dict,
)
In my template userlist.html I have links looking like this (This is where I think the real problem lies):
{%if has_next%}
<a href=page-{{next}}>Next Page> ({{next}})</a>
{%else%}
Instead of replacing the page argument in my url the link adds another page argument to the url. The urls ends up looking like this "/all/a-z/page-1/page-2/
It's not really surprising that this is what happens, but not having page as an optional argument actually works and Django replaces the old page-part of the url.
I would prefer this DRYer (atleast I think so) solution, but can't seem to get it working.
Any tips how this could be solved with better urls.py or template tags would be very appreciated.
(also please excuse non-native english and on the fly translated code. Any feedback as to if this is a good or unwarranted Stack-overflow question is also gladly taken)
You're using relative URLs here - so it's not really anything to do with Django. You could replace your link with:
Next Page> ({{ next }})
and all would be well, except for the fact that you'd have a brittle link in your template, which would break as soon as you changed your urls.py, and it wouldn't work unless category happened to be a-z.
Instead, use Django's built-in url tag.
Next Page> ({{ next }})
To make that work, you'll have to pass your category into the extra_context_dict, which you create on the first line of your view code:
extra_context_dict = { 'category': category }
Is /all/a-z/page-1/page-2/ what appears in the source or where the link takes you to? My guess is that the string "page-2" is appended by the browser to the current URL. You should start with a URL with / in order to state a full path.
You should probably add the category into the extra_context and do:
next page ({{next}})
"Instead of replacing the page argument in my url the link adds another page argument to the url. The urls ends up looking like this "/all/a-z/page-1/page-2/"
that is because
'<a href=page-{{next}}>Next Page> ({{next}})</a>'
links to the page relative to the current url and the current url is already having /page-1/ in it.
i'm not sure how, not having page as an optional argument actually works and Django replaces the old page-part of the url
one thing i suggest is instead of defining relative url define absolute url
'Next Page> ({{ next }})'