Django url dispatcher using repath arguments - python

In my django app . I have endpoints for a package with the months like :
www.example.com/cart/packagename/months
www.example.com/cart/stater/3
which i dont think will good as an url pattern I want something like :
www.example.com/cart/?package=stater&months=3
And also want to encode the parameters 'package=stater&months=3'
If anyone has any suggestions how to achieve that with django let me know. because before i worked with laravel and its pretty simple to do.

Its also very simple to do in Django. The part after question mark here is called URL Query String. You can get its value by:
def cart_view(request):
packages = request.GET.get('package')
months = request.GET.get('months')
As URL query string has nothing to do with actual URL, so you need to change your url.py to:
path('cart/', cart_view,name='cart_view'),

Related

Why do I need to specify HTML file in render()

Why do I need to give html file name in render() - I have already set url in my project file in urls.py in django
urls.py
url('view-books',views.viewBooks)
views.py
def viewBooks(request):
books=models.Book.objects.all()
res=render(request,'BRMapp/view_book.html',{'books':books})
Why can I not give in render view-books?
i think you have typo
def viewBooks(request):
books=models.Book.objects.all()
context = {"books":book}
return render(request,'BRMapp/view_book.html',context)
your question why you need html file name in render because render is a function it takes 3 arguments 1st is request second is "path of the html file" 3rd is the context
further explaination
Do you have basic idea how django work first of first you are not giving url in render you are giving path to render which template should be render . django follow mvc pattern you read on it but to simplify it urls just have the routing task they are just there to filter routes not to do any thing in url you can give 3 arguments two are compulsary first the path by which it recognize that the time has come to act the second the function name which direct him where to go then its function responsibilty to process the data
Unfortunately, you didn't return anything in your view. So you need to add return to your function:
def viewBooks(request):
books=models.Book.objects.all()
return render(request,'BRMapp/view_book.html', {'books':books})
You might want to take a look at this tutorial.
https://yourwebsite/view-book is not the same as BRMapp/view_book.html, Django needs to know that one corresponds to the other.
The routing in Django works like this:
The user sends a request to Django with a url.
Django looks through your urls in urls.py for a path that matches what was requested.
When it finds a path, like view-books, that path has a view. The view is just a function (viewBooks()), and Django executes it.
The view function is expected to return the content that the user will see. You could, if you wanted, write the whole page by hand as a string in the return line of viewBooks(), but that's inconvenient, so instead you tell Django to make the page for you, starting from a template. To do so, you call render().
What render() does is take the template and replace all parts that need to be replaced for the user that will see it. But to know what the initial content will look like, it needs to read it from somewhere, and that's the HTML file BRMapp/view_book.html.
The HTML file doesn't need to have the same name as the view, you could have called it foobar.html and it would have worked the same. But regardless of its name, you need to tell Django that you want to use a file (render() tells Django that), and you need to tell Django where that file is. You'll have many different files in different places with different names, and it can happen that you have the same name for templates in different directories, so Django will not attempt to guess which one you want: you'll have to put its path inside render() so that Django knows where to start building the page.
If you gave the URL to render() instead of the path to the file, Django would get to point 5 and then back again to 1 to figure out what that URL means, and so on and so forth forever.

How to validate and know if an URL is a Google Docs URL? |Python,Flask|

I'm creating a website that has a function to let user share their Google Docs URL to each others. I want to validate the input of the user to be Google Docs URL before I let them post it so that it could be safe. I'm using Flask and Python and I wonder if there is anyway to validate this.
The only validations I learn so far are those from FlaskForm like below:
project_link = StringField('Google Docs link to your project', validators=[DataRequired()])
and to limits the URL's character to 100 in my models.py
I think a possible way to do it is to create some Python codes in my views.py that check if the URL contains phrases like "docs.google.com"...
I don't really know how to validate if an URL is a Google Docs URL and I would greatly appreciate it if you could show me how.
Thank you.
Try something like this:
url = "http://docs.google.com/an/example/google/doc"
prefixes = ["https://","http://"]
def validate(url):
for pre in prefixes:
url = url.strip(pre) # this gets rid of http or https prefixes
if url.startswith("docs.google.com"):
return True
else:
return False
This also has the effect of filtering out any unwanted prefixes, such as "chrome://" or "about://".
An example:
>>> url = "http://docs.google.com/document"
>>> validate(url)
True
>>> url = "https://googledocs.com"
>>> validate(url)
False
>>> url = "prefix://docs.google.com"
>>> validate(url)
False
URL='www......'
if 'docs.google.com' in URL and '&site=' not in URL:
print(True)
As monsieuralfonse64 pointed out, you need the second half of the statement to prevent bypasses where the previous page is listed as containing docs.google.com, but not the other site.
This answer is WRONG. as was once again pointed out, any number of prefixes could be in front of a link, and anything from microsoft.com/hello?x=docs.google.com to stackoverflow.com/docs.google.com?name=hello and youtube.com/watch?v=docs.google.com would all be validated in my approach.
I would like to add one more solution to these already good solutions. For stuff like this you can always just use existing libraries!
Existing libraries probably are accounting for some corner-cases that you haven't thought of yourself (if you chose the right one). We don't want ot re-invent the wheel now, do we?
Here's how I would go about it:
from urllib.parse import urlparse
url = "https://drive.google.nl"
format = "drive.google.com"
parsed = urlparse(url)
if(parsed.netloc == format and (parsed.scheme == "http" or parsed.scheme == "https")):
print(True)
I only tested this in python3, but I'm sure it'll also work for other python versions.

Remove whitespaces from a url in Urlpatterns (django)

I'm new to Django and I'm developing a project in which there are profile pages.
Well, the problem is that the primary key has whitespaces but I don't want them to show in the url, neither like "%20%", I want to join the words. For example:
website.com/Example Studios --> website.com/examplestudios
I've tried this:
url ( (r'^(?P<studio_name>[\w ]+)/$').replace(" ", ""), views.StudioView, name = 'dev_profile')
But didn't work (it seems like it turns the raw part to string before reading the url) and with 're' happens the same. I've been searching for solutions but I'm not able to find them (and slugify doesn't convinces me).
What's solution to this or what do you recommend?
In urls you define patterens which Django will catch e.g. r'^test/$' this means that when someone try to get yourdomain.com/test Django will catch it and call the view which will probably render template. You need to solve your problem on url generation e.g. in template . Therefore in urls:
url ( (r'^(?P<studio_name>[\w ]+)/$'), views.StudioView, name = 'dev_profile').
You need to transform primary key to word without space in template. One way is to use slug for every record.
Also add slug field to Studio model which is autogenerated and non-editable field(you can generate it from name e.g. Example Studios->examplestudios).

How do I create a 'urlpattern' with an indefinite amount of 'named regex groups'

Explanation
I want to have a folder type structure with my website urls, like this example:
www.sitename.com/catagory/sub-catagory/another-catagory/yet-another
currently inside my urls.py I have the following urlpattern to begin to describe this:
url(r'^(?P<slug>[a-zA-Z0-9-\/]+)/', views.page_view)
My Problem
The url seems to only get the last part of the url, so if I entered the following
www.sitename.com/catagory/sub-catagory/another-catagory/yet-another
it only seems to capture
yet-another
I've got no idea how to fix this, any help would be very appreciated :)
This seems to work correctly
# urls.py
url(r'^(?P<slug>[a-zA-Z0-9-\/]+)/', views.page_view)
# views.py
def page_view(request, slug):
slug #
For a url www.example.com/a/b/c/d it'll capture a/b/c which can be split at /.
For a url www.example.com/a/b/c/d/ it'll capture a/b/c/d

Python Django: urls.py questions

Need a little help with my urls.py and other stuff.
How can I replicate this in Django?
1) When user requests a non-existent page it will redirect to one up the directory level. Ex: example.com/somegoodpage/somebadpage should be redirected to example.com/somegoodpage.
2) When user requests page example.com/foo/bar/?name=John it will make url to example.com/foo/bar/name=John
3) When user requests page example.com/foo/bar/John it will change url to example.com/foo/bar/name=John.
Any help is greatly appreciated. Thank You.
For 1), if you don't want to do a separate route for every single route on your website, you'll need middleware that implements process_exception and outputs an HttpResponseRedirect.
For 2 and 3, those are rules that are presumably limited to specific routes, so you can do them without middleware.
2 might be doable in urls.py with a RedirectView, but since the relevant bit is a query string argument, I would probably make that an actual view function that looks at the query string. Putting a ? character in a url regex seems strange because it will interfere with any other use of query strings on that endpoint, among other reasons.
For 3, that's a straightforward RedirectView and you can do it entirely in urls.py.
according to django doc for number 1:
django URL dispatcher runs through each URL pattern, in order, and stops at the first one that matches the requested URL, so add a pattern that matches "somebadpage"s and assign it to a view which redirects the user to "somegoodpage".
for number 2:
the doc says "The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name."
so i don't think that you can get the "?name=John" in url dispather, so if you describe what you want to do maybe I can help better
and for 3:
to capture bits of the URL and pass them as positional arguments to a view you should use named regular-expression groups, for example :
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', 'news.views.month_archive'),
and the request to /articles/2005/03/ would call the function news.views.month_archive(request, year='2005', month='03'), instead of news.views.month_archive(request, '2005', '03').
hope this helped :)

Categories