How to run a function in Django?

Serve a Django App from an AWS Lambda Function - Lawrence McDaniel

DJANGO FUNCTIONS

In this article, we will describe you about django functions.these functions are playing a important role in django.These functions use in the biggest and  perfect projects mostly developers use these functions in django API’S,DATABASE’S and other  places.

These functions Iam going to describe are very usefull for developers.so,read carefully because iam decrive mostly used functions in django.

Anyway let’s start our tutorials on django functions,which are used mostly in biggest applications but first we hav to understand the basic of functions :-

Functions in Python


A function is a set of statements that take inputs, and do some computational works on them according to the developer describe.It’s main work is do some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function.

Python provides some built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.

def func( x ):
       if(x %2==0):
             print("even")
      else:
            print("odd”)

func(2)
func(3)

output:-
even
odd

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

The Anonymous Functions

These functions are called anonymous because they are not declared in the manner by using the def keyword. You can use the lambda keyword to create anonymous functions.
·      Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
·      An anonymous function cannot be a direct call to print because lambda requires an expression
·      Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
·      Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.

Syntax

The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −


sum = [lambda arg1, arg2: arg1 + arg2]


print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
When the above code is executed, it produces the following result −
Value of total :  30
Value of total :  40
DJANGO FUNCTIONS
Python's range() Function Explained | Django Central

In Django we use functions in Views to create a django project API.here we describe these function based views for   
the developers, who want to know everything about Django Functions.


These functions are very easy to implement and it’s very useful but the main disadvantage is that use only on a large Django project, usually a lot of similar functions in the views . If all objects of a Django project usually have CRUD operations so this code is repeated again and again unnecessarily and this was one of the reasons that the class-based views and generic views were created for solving that problem.
def create_view(request, pk):
template_name = 'form.html'
form_class = MyForm
form = form_class

if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('view'))
return render(request, template_name, {'form': form})

The package django collects functions and classes that makes multiple MVC in django projects.
Now lets see the functions we use mosly:-

Render()

Syntax:-

render(request, template_name, context=None, content_type=None)

Required arguments :-

request
The request object used to generate the response.

template_name
Here you will just give your template name with full path like newapp/template/index.html.

Optional arguments :-

context
A dictionary of values to add to the template context. By default, this is an null dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.
content_type
The MIME type to use for the resulting document. Defaults to 'text/html'.

from django.shortcuts import render

def my_view(request):

return render(request, 'new/appindex.html', {
'foo': 'bar',
}, content_type='application/xhtml+xml')
--------------------or----------------------------
from django.http import HttpResponse
from django.template import loader

def my_view(request):

var1 = loader.get_template('newapp/index.html')
var2 = {'foo': 'bar'}
return HttpResponse(var1.render(var2, request), content_type='application/xhtml+xml')

redirect()

Syntax:-
redirect(to, *args,**kwargs)
Returns an HttpResponseRedirect to the appropriate URL for the arguments passed.
The arguments could be :-
·      A model: the model’s get_absolute_url() function will be called.
·      A view name, possibly with arguments: reverse() will be used to reverse-resolve the name.
·      An absolute or relative URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass permanent=True to issue a permanent redirect.
You can use the redirect() function in a number of ways.
1.    By passing some object; that object’s get_absolute_url() method will be called to the redirect URL:-
from django.shortcuts import redirect

def my_view(request):
...
obj = MyModel.objects.get(...)
return redirect(obj)
2.    By passing the name of a view and optionally some positional or keyword arguments; the URL will be reverse resolved using the reverse() method:-
def my_view(request):
...
return redirect('some-view-name', foo='bar')
3.    By passing a hardcoded URL to redirect to:-
def my_view(request):
...
return redirect('/some/url/')
This also works with full URLs:-
def my_view(request):
...
return redirect('https://example.com/')
By default, redirect() returns a temporary redirect. All of the above forms accept a permanent argument; if set to True a permanent redirect will be returned:
def my_view(request):
...
obj = MyModel.objects.get(...)
return redirect(obj, permanent=True)

get_object_or_404()

Syntax:-
get_object_or_404(*args, **kwargs)
Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.

Required arguments:-


**kwargs
It is used when you will used as a dictionary in django.
The following example gets the object with the primary key of 1 from MyModel:
from django.shortcuts import get_object_or_404

def my_view(request):
obj = get_object_or_404(MyModel, pk=1)
------------------------OR--------------------------------------
from django.http import Http404

def my_view(request):
try:
obj = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
However, you can also pass a QuerySet instance:
queryset = Book.objects.filter(title__startswith='M')
get_object_or_404(queryset, pk=1)
The above example is a bit contrived since it’s equivalent to doing:
get_object_or_404(Book, title__startswith='M', pk=1)
but it can be useful if you are passed the queryset variable from somewhere else.
Finally, you can also use a Manager. This is useful for example if you have a custom manager:
get_object_or_404(Book.dahl_objects, title='Matilda')
You can also use related managers:
author = Author.objects.get(name='Roald Dahl')
get_object_or_404(author.book_set, title='Matilda')
Note: As with get(), a MultipleObjectsReturned exception will be raised if more than one object is found.

get_list_or_404()

Syntax:-
get_list_or_404( *args, **kwargs)
Returns the result of filter() on a given model manager cast to a list, raising Http404 if the resulting list is empty.

Required arguments:-


**kwargs
Lookup parameters, which should be in the format accepted by get() and filter().
The following example gets all published objects from Model:-
from django.shortcuts import get_list_or_404

def my_view(request):
my_objects = get_list_or_404(MyModel, published=True)
---------------------------------------OR------------------------------------------
from django.http import Http404

def my_view(request):
my_objects = list(MyModel.objects.filter(published=True))
if not my_objects:
raise Http404("No matches in the model is given ….")

Now we will see some function in django.these functions used mostly in all over the django projects.

Database Functions

Django Function-Based Views vs. Class-Based Views - concise coder

The classes documented below provide a way for users to use functions provided by the underlying database as annotations, aggregations, or filters in Django. Functions are also expressions, so they can be used and combined with other expressions like aggregate functions.


We’ll be using the following model in examples of each function:
class Author(models.Model):
name = models.CharField(max_length=50)
age = models.PositiveIntegerField(null=True, blank=True)
text_contents = models.CharField(max_length=50, null=True, blank=True)
content = models.CharField(max_length=50, null=True, blank=True)
We don’t usually recommend allowing null=True for CharField since this allows the field to have two “empty values”, but it’s important for the Coalesce example below.

Date functions

Django Class-Based Views: The Basics | Imaginary Landscape

This date functions are use when we want to use some date related things in the django projects.well, mostly this use in datasbase.

We’ll be using the following model in examples of each function:
class Mode(models.Model):
start_with_datetime = models.DateTimeField()
start_with_date = models.DateField(null=True, blank=True)
start_with_time = models.TimeField(null=True, blank=True)
end_with_datetime = models.DateTimeField(null=True, blank=True)
end_with_date = models.DateField(null=True, blank=True)
end_with_time = models.TimeField(null=True, blank=True)

There are many more functions to describe you but in this article this will not be possible.so,enough for now but I describemain functions whch will be very usefull for our django developers brothers.


Reactions

Post a Comment

0 Comments