Basic urls
from django.conf.urls import url
from boards import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
]
Deeper URL structures:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^about/company/$', views.about_company, name='about_company'),
]
Advanced urls (with regex) eg: this will create a url of each username
from django.conf.urls import url
from boards import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^(?P[\w.@+-]+)/$', views.user_profile, name='user_profile'),
]
Parameters
1. Parameters as part of url: eg: /users/5
url(r'^users/(?P\d+)/$', 'viewname', name='urlname')
Function-based view
def viewname(request, user_id):
user = User.objects.get(id=user_id)
Class-based view
class SampleView(TemplateView):
def get_context_data(self, **kwargs):
user = User.objects.get(id=kwargs['user_id'])
2. GET parameters eg: /products?price_lte=5000
url(r'^products/$', 'viewname', name='urlname')
def viewname(request):
price_lte = request.GET['price_lte']
3. POST parameters
url(r'^register/$', 'register', name='urlname')
def register(request):
form = RegisterForm()
if request.method == "POST":
form = RegisterForm(request.POST) #if no files
if form.is_valid():
#do something if form is valid
context = {
'form': form
}
return render(request, "template.html", context)
Match string after drinks/ prefix
path('drinks//',...),
Match one or more characters (non-digit regular expression) after drinks/ prefix
re_path(r'^drinks/(?P\D+)/',...),
Match integer after stores/ prefix
path('stores//',...),
Match one or more digits (digit regular expression) after stores/ prefix
re_path(r'^stores/(?P\d+)/',...),