How to modify the link to access user profile? - django

I would like to modify the url to access user profile. OSQA use permalink() to generate the profile url
The default link is http://meta.osqa.net/users/2836/nhatthinh
And I want to change it to http://meta.osqa.net/users/nhatthinh
So, I modify the function get_profile_url follow as:
#models.permalink
def get_profile_url(self):
return ('user_profile', [slugify(self.username)])
And I also modify the url in forum\urls.py follow as:
url(r'^%s/(.*)/$' % _('users/'), app.users.user_profile, name='user_profile'),
But the result falls short of my expectation.
OSQA generates a link is http://meta.osqa.net/users//nhatthinh
So, how can I fix this issue?
Thank you so much.

You might want to try it like that:
url(r'^%s/(.*)/$' % _('users'), app.users.user_profile, name='user_profile'),
And if you use tranlsations, do not forget to adapt these as well.

Related

How to append string in the end of Django redirect in view?

I have a product on my platform and when a specific user does an action, I want to redirect them to example.com/product/product-slug/#SectionInWebsite.
However, I am not able to find a way to append "#SectionInWebsite" to the end of the redirect function.
return redirect('ProductSingle', product.slug, "#SectionInWebsite")
This worked for me (I had to use different names on my machine, but it should work):
# views.py
return redirect('{}#sectionInWebsite'.format(reverse('ProductSingle', kwargs={'product_slug':product.slug})))
That is, assuming your urls.py has something like this:
# urls.py
...
path('ProductSingle/<str:product_slug>', views.ProductSingle, name='ProductSingle'),
...
This is just a variation of the answer provided here, applied to your situation.
do this :
return redirect(reverse('ProductSingle',product.slug) + '#SectionInWebsite')
Maybe this can help you, using reverse.
return redirect(reverse('ProductSingle', product.slug) + '#SectionInWebsite')

Wagtail - Override internal links in richtexteditor

Since I use wagtail headlessly the internal links get messed up due to them using the site-url listed in settings. Instead, I want to be able to override that same URL and point them to my frontend.
This post talks a little bit about it in 2018, but I'm hoping this has changed?
Wagtail: Is it possible to disable prepending internal link's with the site domain?
For external links you'd do something like this to override it:
class NewWindowExternalLinkHandler(LinkHandler):
# This specifies to do this override for external links only.
identifier = 'external'
#classmethod
def expand_db_attributes(cls, attrs):
href = attrs["href"]
print(attrs)
# Let's add the target attr, and also rel="noopener" + noreferrer fallback.
# See https://github.com/whatwg/html/issues/4078.
return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href)
Is it possible to do the same for internal links?
E.g now since I use a multi-site setup my link looks something like:
https://localhost.my-backend-api-domain.com/page/pagename
I want it to look like this:
https://my-frontend-domain.com/page/pagename
Also I was struggling to change the behaviour of the internal page links.
Intuitivly one would think to follow the external-link example and seethe identifier to external.
That's however not the case. After digging further into the source I was able to change the behaviour of the external link like this:
from django.utils.html import escape
from wagtail import hooks
from wagtail.rich_text.pages import PageLinkHandler
from wagtail.models import Page
class TargetNewInternalLinkHandler(PageLinkHandler):
#classmethod
def expand_db_attributes(cls, attrs):
try:
page = cls.get_instance(attrs)
return '<a href="%s" class="uk-link uk-link-text">' % escape(page.localized.specific.url)
except Page.DoesNotExist:
return "<a>"
#hooks.register('register_rich_text_features')
def register_external_link(features):
features.register_link_type(TargetNewInternalLinkHandler)
I know this doesn't exactly answer your question. But does it help you figure out a solution?

What is best practice for passing variables via GET?

I am passing a variable in my URL:
mydomain.com/app/?next_page=my_page
I can get this variable in a view with:
def mypage(request):
var = request.GET['next_page']
Is it best practice to also change the URL to require next_page? Something along the lines of:
path('app/?nextpage=<str>', mypage, name='my_page')
What's best practice? If so, what's the correct syntax for this (I know the example is incorrect)?
It depends on your needs.
Do not define a fixed url route; if you use the query parameters for filtering and there is more than one possible parameter
Example: "app/photos?size=100x100" and "app/photos/?color=blue"
Define a fixed url route; if it will be the same for each and every page, like details of a particular page:
Example: "app/orders/123123123" and "app/orders/123123123"
Btw, the correct syntax is:
path(app/<str:next_page>/, mypage, name="my_page")
You should take a look at path patterns. Enforcing a GET parameter in a path is not really a good practice. So if you want to require a username for example you can use:
path('bio/<username>/', views.bio, name='bio'),
You can find more patterns in Django documentation to catch strings, slugs, integers etc.
And in views you should define your function as such:
def mypage(request, username):
...code...
About GET:
Keep in mind that request.GET["value"] will raise a ValueError if that parameter does not exist. So you can catch that error to inform user that they are missing a parameter. (This will make this parameter obligatory.)
You can also use request.GET.get("value") which will return None if the key does not exist. If you want to use a default parameter you can use of course, request.GET.get("value", "default")
You can use as many parameters as you want in your link with or without path patterns. Their values will be stored in request.GET

How to use variable at start of django url to return to view?

I am trying to pass the first part of a django url to a view, so I can filter my results by the term in the url.
Looking at the documentation, it seems quite straightforward.
However, I have the following urls.py
url('<colcat>/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'),
url('<colcat>/', views.collection_view, name='collection_view'),
In this case, I want to be able to go to /living and have living be passed to my view so that I can use it to filter by.
When trying this however, no matter what url I put it isn't being matched, and I get an error saying the address I put in could not be matched to any urls.
What am I missing?
<colcat> is not a valid regex. You need to use the same format as you have for name.
url('(?P<colcat>[\w\-]+)/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'),
url('(?P<colcat>[\w\-]+)/$', views.collection_view, name='collection_view'),
Alternatively, use the new path form which will be much simpler:
path('<str:colcat>/collection/<str:name>', views.collection_detail, name='collection_detail'),
path('<str:colcat>/', views.collection_view, name='collection_view'),

Parse url with jinja

In jinja, I can do {{request.path}} to get the url.
However, i have a token, that is dynamic, so i can't check the entire url.
/users/review/step2/c/DqBJjAZ4PdmpfhzbXBc5g9
/users/review/step2/u/DqBJjAZ4PdmpfhzbXBc5g9
My question is about identify the part with /c/ or /u/. c is create and u update.
After that i can build an url_for using c or u accordingly the url. What is the best way to identify if the url is to create or update?
I would suggest just passing a variable to your template to be used in the template.
so
#app.route('/users/review/step2/c/<token>')
def if_template(token):
return render_template(
"template.jinja2",
create=True)
#app.route('/users/review/step2/u/<token>')
def if_template(token):
return render_template(
"template.jinja2",
update=True)
if you're only two states are create and update than one variable will probably suffice.