Python‎ > ‎django‎ > ‎django.conf‎ > ‎

urls


Example
The registration form is created using models in which user is allowed to register for news letter. model.py fields are import into the forms.py using class Meta.

Window CMD  commands 

  • virtualenv pythonlake
  • cd  pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py syncdb
  • python manage.py runserver

Files


mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','myapp',
) 

mysite/urls.py

from django.contrib import admin
admin.autodiscover()
from myapp.views import Register, Response

urlpatterns = patterns('',
    # Examples:
    url(r'^$', Register),
     url(r'^thanks/$', Response),

    url(r'^admin/', include(admin.site.urls)),
)

myapp/admin.py

from django.contrib import admin

from .models import Reg

    class Meta:
        model=Reg

admin.site.register(Reg,RegAdmin)

myapp/models.py

from django.db import models
class Reg(models.Model):
    first_name=models.CharField(max_length=100)
    last_name=models.CharField(max_length=100)
    email=models.EmailField()
    

myapp/forms

from django import forms
from .models import Reg

class RegForm(forms.ModelForm):
    class Meta:
        model=Reg

myapp/views.py

from django.shortcuts import render
from .forms import RegForm
from django.http import HttpResponse

def Register(request):

    form=RegForm(request.POST)
    if form.is_valid():
        save_form=form.save(commit=False)
        save_form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=RegForm()

    return render(request, 'myapp\index.html', {'form':form})

def Response(request):
    return HttpResponse('Thanks for registering with us')

myapp/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<h1> Register for latest news</h1>

<form  action="" method="post">

    {%csrf_token%}

    {{form.as_p}}

    <input type="submit">

</form>

</body>
</html>





Example
Here in this example, the CharField  is used to store the data into the field.  The data is recorded and saved in models.py and retrieved and displayed through the views.py. 
 Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv djangoschool
  • cd djangoschool
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp dbapp
  • python manage.py makemigrations dbapp


mysite/settings,py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','dbapp',
)

mysite/urls.py

from django.conf.urls import include, url

from dbapp.views import Display

urlpatterns = [
    url(r'^', Display),
]

dbapp/models.py


    groups=(('male','0-40'),('female','0-40'))
    genderfield=models.CharField(max_length=50,choices=groups)

v=LongLife(genderfield="Casey")
v.save()

dbapp/views.py



from . models import LongLife

def Display (request):
    return HttpResponse(LongLife.objects.filter(genderfield="Casey").values())









Here, this examples, mydb.db database is created and in that database Table3 is created with Fields, name, email, telephone and income. The values are displayed through for loop by order of income in html file.
Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv pythonlake
  • cd pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp mydb
  • python manage.py makemigrations mydb




mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','mydb',
)

mysite/urls.py


from mydb.views import DataBase
urlpatterns = [
    url(r'^$', DataBase),
]

mydb/views.py

from django.shortcuts import render

import sqlite3

def DataBase (request):
    conn=sqlite3.connect('mydb.db')
    cursor=conn.cursor()
    cursor.execute('''CREATE TABLE table3(name text, phone text, email text, income text)''')
    cursor.execute('''INSERT INTO table3 VALUES(' Erica ', ' 571 402 2992 ', ' erica.steve@ibm.com ', '  180000 ')''')
    cursor.execute('''INSERT INTO table3 VALUES(' Strube ', ' 571 402 2212 ', ' marya_strube@care.com ', ' 890000 ')''')
    conn.commit()

    for row in cursor.execute('SELECT * FROM table3 ORDER BY income'):
        response=row

    return render(request, 'mydb\index.html', {'response':response} )

mydb/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Table3</title>
</head>
<body>

{{response}}

</body>
</html>





Here, this examples, mydb.db database is created and in that database Table3 is created with Fields, name, email, telephone and income. The values are displayed through for loop by order of income in html file.
Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv pythonlake
  • cd pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp mydb
  • python manage.py makemigrations mydb




mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','mydb',
)

mysite/urls.py


from mydb.views import DataBase
urlpatterns = [
    url(r'^$', DataBase),
]

mydb/views.py

from django.shortcuts import render

import sqlite3

def DataBase (request):
    conn=sqlite3.connect('mydb.db')
    cursor=conn.cursor()
    cursor.execute('''CREATE TABLE table3(name text, phone text, email text, income text)''')
    cursor.execute('''INSERT INTO table3 VALUES(' Erica ', ' 571 402 2992 ', ' erica.steve@ibm.com ', '  180000 ')''')
    cursor.execute('''INSERT INTO table3 VALUES(' Strube ', ' 571 402 2212 ', ' marya_strube@care.com ', ' 890000 ')''')
    conn.commit()

    for row in cursor.execute('SELECT * FROM table3 ORDER BY income'):
        response=row

    return render(request, 'mydb\index.html', {'response':response} )

mydb/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Table3</title>
</head>
<body>

{{response}}

</body>
</html>





Here, in this example, the IntegerField validated number entered should be in record and before the Field vale is passed on HttpResponseRedirect in views.py and index.html files.
Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myvirtualenv
  • cd  mysite
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapphttp
  • python manage.py runserver 



setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','myapphttp',
)

urls.py

from django.conf.urls import include, url

from myapphttp.views import response

urlpatterns = [
      url(r'^', response),
]

myapphttp/forms.py

from django import forms



def Validate(value):
    pin=[1101,2945,3635,5550,3334,5553,2822,4624,3221,6453,2223,4456,5462]
    if value not in pin:
        raise ValidationError('%s : The pin number is not in our record.'% value)

class IntegerField(forms.Form):
    number=forms.IntegerField(label='Number' ,validators=[Validate])

myapphttp/views.py

from django.shortcuts import render

from .forms import IntegerField

def response(request):
    if request.method == 'POST':
        form=IntegerField(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/Thanks-for-submitting-your-request/')
    else:
        form = IntegerField()

    return render(request, 'myapphttp\index.html', {'form':form})


myapphttp/index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

<form action="/pin-not-found/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

</body>
</html>





Here, in this example, the form validation is processed through the calling the function in the forms.EmailField(). The  function validated the list items after the form is submitted through POST method.
 Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myenv
  • cd  myenv
  • .\Scripts\activate
  • .\Scripts\deactivate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py runserver

Files


setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', 'myapp', 
)

urls.py

from myapp.views import submit

urlpatterns = [
    url(r'^', submit),
]

myapp/forms.py

from django import forms
from django.core.exceptions import ValidationError

def Validate(email):
    list=['adil@adilwaseem.com', 'adil@pythonlake.com','contact@adilwaseem.com']
    if email not in list:
        raise ValidationError("%s is not in our record."% email )

class AccessForm(forms.Form):
    email=forms.EmailField(label='Email',validators=[Validate])

myapp/views.py

from django.shortcuts import render

from .forms import AccessForm

def submit(request):
    if request.method == 'POST':
        form=AccessForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = AccessForm()

    return render(request, 'myapp\index.html', {'form':form})

myapp/index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

<form action="/Response/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

</body>
</html>

view at localhost:8000/










EXAMPLE 
Here, the submit form is created through the django web framework using django.forms. The forms is handled through the HTML files in which the views.py variables data is processed. While views.py import the form fields from myapps/forms.py
Steps for creating steps for virtua 

Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myenv
  • cd  myenv
  • .\Scripts\activate
  • .\Scripts\deactivate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py runserver

Files



Settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', 'myapp'
)


mysite/urls.py

from django.conf.urls import url
from myapp.views import submit

urlpatterns = [
    url(r'^', submit),
]


myapp/forms.py

__author__ = 'adilwaseem75'

from django import forms

class CharField(forms.Form):
    username=forms.CharField()
    username.label="Username"
    username.max_length=50

class EmailField(forms.Form):
    email=forms.EmailField()
    email.label="Email"
    email.max_length=50


myapp.views.py

from django.shortcuts import render

from .forms import EmailField
from .forms import CharField

def submit(request):
    username=CharField()
    email=EmailField()

    return render(request, 'myapp\index.html', {'username':username, 'email':email})

myapp.index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

<form action="/Thank-you/" method="post">
    {% csrf_token %}
    {{username}} <br> <br>
    {{email}}<br><br>
    <input type="submit" value="Submit" />
</form>

</body>
</html>


Running the server through Window CMD command, python manage.py runserver






EXAMPLE
The django web framework is used to create the application which convert the string into uppercase using str.upper method. The string_method_upper.py calls the string_method.views.py file to render the function.
Windows CMD commands for creating virtualenv, startproject, startapp, and running server.
  • virtualenv string
  • cd string
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject str
  • cd str
  • python manage.py runserver
  • python manage.py startapp string_methods
  • python manage.py startapp string_method_upper
  • python manage.py runserver



string_method_upper/views.py


def string_method_upper (request):
    return string_upper(request)

string_methods/views.py


def string_upper(request):
    return HttpResponse("Python is a simple, powerful and high-level programming language "
                        "and the logic and structure is consistent with the way we "
                        "reasons. ".upper())


urls.py

from string_methods.views import*
from string_method_upper.views import *

urlpatterns=patterns('', url(r'^string_method_upper/', string_method_upper),)

settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','string_methods', 'string_method_upper',
)





Example
The app is created to count the words in string using django web framework.
 Django Window CMD Commands
Steps for creating virtual environment, startproject, startapps, migration, & running server:
  • virtualenv string
  • cd  string
  • .\Scripts\activate
  • .\Scripts\deactivate
  • pip install django
  • python .\Scripts\django-admin.py startproject str
  • cd str
  • python manage.py runserver
  • ctr c to stop server
  • python manage.py startapp string_methods
  • python manage.py migrate
  • python manage.py runserver
FILE STRUCTURE
 
In views.py file, the string value is added  by '%' expression to add str.count(). 
from django.http import HttpResponse

def count_chr(request):

    x="Python Lake is a project of OnRails LLC, founded by Adil Waseem with a mission to put all" \
      " Python Programming codes in one website with research findings for beginner, developer and " \
      "researcher to advance the development of Python. Internet is flooded with the Python codes but" \
      " all are deficient in comprehensiveness where we could find all functions in place with the" \
      " examples how and where to apply these. Python Lake will achieve this mission to promote learning" \
      " and research of Python without constraint by the lack of code examples and its application. " \
      "The site will be kept update periodically to allow students, developer and researcher them make" \
      " best of available resources in Python."
    y=x.count('Python')
    response = "Total words start with 'Python' in paragraphs are:%s"
    return HttpResponse(response%y)
 
In settings.py file,  apps name is added.
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','string_methods'
)
In urls.py file, following code is added to allow the apps to import function from the views.py.
 from django.conf.urls import include, url
from django.contrib import admin

from string_methods.views import count_chr

urlpatterns = [
    url(r'^string_methods/', count_chr),
]
 
Viewing in the browser after running server through CMD command.
 
 


Subpages (3): include patterns url
Comments