Django url parameter passing - python

I am not even sure what category in Django this question falls in and I am very new to django. I have tried looking for Django post requests, parameter passing and even checked under Django APIs but have not found what I am looking for. What I am trying to do is create an API for my client but it must be done in Django. If I was to do this in .Net I could use http post and http get and web services but I am not at all sure how this is done in Django. What my client wants to do is to be able to see:
Enter username and password in url with parameters for date and id and be able to view rooms available based on what is entered
Enter username, password and dates and room code to be able to book the room
No interface needed just simple parameter passing through url. Is this possible with Django and if yes can somebody please point me in the right direction.

What you're looking for are captured parameters
Below is a code snippet from the above link.
# urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('blog.views',
url(r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
)
# views.py
def year_archive(request, year, foo=None):
# view method definition

As of Django 1.10, patterns was removed from Django.
Here is a 2019 Django 2.2 solution.
It looks like re_path is the current recommended tool for capturing parameters via regular expressions:
https://docs.djangoproject.com/en/2.2/ref/urls/#re-path
# urls.py
from django.urls import re_path
from myapp import views
urlpatterns = [
re_path(r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}),
]
# views.py
def year_archive(request, year, foo=None):
# view method definition

Related

redirection from old urls to new urls

Hello everyone I want to redirect URLs like this
from
https://www.example.co.uk/pages/terms-conditions
to
https://www.example.co.uk/terms-conditions
I developed the updated site using the Django framework and now want to redirect old site URLs to new URLs and not losing traffic. what is the best way of doing…?
New site is not published it is on local machine
my view.py
my urls.py
I guess this is not best practice but you can just redirect the user to the right url if he hits the other one in your views.py like:
def old_view(request):
return redirect('https://www.example.co.uk/terms-conditions')
def new_view(request):
return render(request, "your_app/conditions.html")
with urls.py like:
path('pages/terms-conditions/', views.old_view, name='old_view')
path('terms-conditions/', views.new_view, name='new_view')
Assuming you want to remove the application name from the urls. In your project's urls.py NOT your applications urls.py. You should have a line similar to the following:
path('pages/', include('pages.urls', namespace='pages')),
replace the 'pages/' with just ''.
Note: Using the pages/ allows you to provide segregation between your applications to ensure the urls do not conflict

How to override a Django url path that is provided by a library?

I'm currently building out an authentication server using Django, djangorestframework, and django-rest-auth. My problem is actually pretty simple I think, but I haven't really been able to find any resources on it.
Here's my issue, in django-rest-auth there is a specific url to change a user's password, which is /rest-auth/password/reset/. I'd like the url to instead be /auth/password/change/, but don't want to edit the library code to do so.
The issue is that as of now, in my url.py file, I have the rest-auth urls imported as such:
from django.urls import path, include
urlpatterns = [
path('', include('rest_auth.urls')),
]
So it just imports the urls as written in the library. How can I change the specific url to what I want?
You just need to add a url like this
path('/auth/password/change/', your_view)
your_view will be same as view of /rest-auth/password/reset/ which is PasswordResetView.

blocking unwanted urls in django

I have added account app to installed_apps in my django project.
also I have added urls of account app as like below:
(r"^account/", include("account.urls"))
Its working fine.
Now I had to override SignupView class of account app. This is also working fine.
Now I have created a new class CreateUser(SignupView) and I want that only admin user will be able to create user. So I added a different url for CreateUser(SignupView) view.
Now I want that account/signup url with view SignupView will not be accessible anymore.
How can I block this particular url by keeping other urls active of account app as this is a library.
You can add a specific entry for the one URL that you wish to block before you include the packages urls.py. This will take precedence as Django loops over URLs in order looking for the first match
from django.views.generic.base import RedirectView
urlpatterns = [
path('account/signup', RedirectView.as_view(url='/')),
path('account', include('account.urls')),
]

DRF does not reverse Django url pattern: NoReverseMatch

There is a complex app (not possible to just paste the code). Going to try to explain.
Django
There is a urls.py file from the native Django app. The urlpatterns defines and register its urls. The ^foo/ defines a group of related urls and the foonamepsace.
urlpatterns = patterns('',
...
url(r'^foo/', include('foo.urls', namespace='foonamespace')),
...
Now there is a method generate_report which does some logic inside and then uses render_to_string to return the HTML:
def generate_report(..):
...
return render_to_string('foo/foo_report.html', args)
Everything works inside the app, the url get reversed successfully.
Django Rest Framework (DRF)
Now there is a DRF implementation and one of its resources is supposed to return a report in a binary format.
class PDFReportViewSet(APIView):
renderer_classes = (BinaryFileRenderer, )
def get(..):
...
pdf = generate_report() # <-- fails with NoReverseMatch
...
return response
Problem
The ViewSet calls the generate_report, however one gets an error when trying to parse the HTML:
NoReverseMatch: foonamespace' is not a registered namespace
Question
Any clues why DRF cannot reverse the namespcae/url from the the core of Django app? How to make sure DRF can reverse a namespace from the core urls.py urlpattern?
Added
After investigation, inside the foo_report.html any usage of the url, for example {% url 'foonamespace:123' %} or {% url 'barnamespace:123' %} produces the error - only if ran from the DRF (running the same page using native Django works fine).
URLS
foo.urls.py
from django.conf.urls import patterns, url
from foo.views import (FooListView, FooDetailView...)
urlpatterns = patterns('',
url(r'^$', FooListView.as_view(), name='foo_list'),
url(r'^(?P<pk>\d+)/$', FooDetailView.as_view(), name='foo_details'),
Important note. The app is served at some.domain.com/, while the REST is served from some.domain.com/rest. So may be this way /rest just don't include anything because it is a parent of the root (which includes the foo.urls.py)
I was managed to resolve my issue with the help from #dirkgroten. It was difficult to see the problem without looking at the source code.
Solution
Updated the routers.py file:
urlpatterns = router.urls
urlpatterns += patterns('',
url(r'^foo/', include('foo.urls', namespace='foonamespace')),
)
Explanation
Basically, the app was serve from the root url / while the rest was served from /rest. The DRF router simply didn't include any of the root routes. Adding them manually like it is shown in solution resolved the problem and made foonamespace visible for all DRF elements.

Customized views with django-registration

I need to make a very simple modification -- require that certain views only show up when a user is not authenticated -- to django-registration default views. For example, if I am logged in, I don't want users to be able to visit the /register page again.
So, I think the idea here is that I want to subclass the register view from django-registration. This is just where I'm not sure how to proceed. Is this the right direction? Should I test the user's authentication status here? Tips and advice welcomed!
Edit
I think this is the right track here: Django: Redirect logged in users from login page
Edit 2
Solution:
Create another app, for example, custom_registration, and write a view like this (mine uses a custom form as well):
from registration.views import register
from custom_registration.forms import EduRegistrationForm
def register_test(request, success_url=None,
form_class=EduRegistrationForm, profile_callback=None,
template_name='registration/registration_form.html',
extra_context=None):
if request.user.is_authenticated():
return HttpResponseRedirect('/')
else:
return register(request, success_url, form_class, profile_callback, template_name, extra_context)
I had to use the same function parameters, but otherwise just include the test, and if we pass it, continue to the main function.
Don't forget to put this in your URLConf either (again, this includes some stuff about my custom form as well):
top-level URLConf
(r'^accounts/', include('custom_registration.urls')),
(r'^accounts/', include('registration.urls')),
custom_registration.views
from django.conf.urls.defaults import *
from custom_registration.views import register_test
from custom_registration.forms import EduRegistrationForm
urlpatterns = patterns('',
url(r'^register/$', register_test, {'form_class': EduRegistrationForm}, name='registration.views.register'),
)
As far as I remember django-registration is using function-based views, so you can not really subclass them. The approach I usually follow is "overwriting" the original views (without modifying the django-registration app of course). This works like this:
Create another app (you could call it custom_registration or whatever you want)
This app need to contain another urls.py and in your case another views.py
Copy the original register view code to your new views.py and modify it, add a pattern to your urls.py to point to this view (use the same url pattern as in django-registration for this view)
Put an include to your projects urls.py of your new app urls.py before your are including the original django-registration app. This could look like this for example:
urlpatterns = patterns('',
...
url(r'^accounts/', include('custom_registration.urls')),
url(r'^accounts/', include('registration.backends.default.urls')),
...
)
This simply works since the first matching url pattern for /accounts/register will point to your new app, so it will never try to call the one from the original app.

Categories

Resources