Posted: March 10th, 2010 | Author: Davo | Filed under: Django | Tags: instance, objecttype, type, typeof | 1 Comment »
In some circumstances it is useful to know what type() / instance the object is.
Python provides 2 useful built in functions which can be handy for this kind of operations.
>>> from apps.deals.models import Deal
>>> deal = Deal.objects.get(id=1)
>>> type(deal).__name__ # retrieve the name of the class
'Deal'
>>> type(Deal()).__name__ # same
'Deal'
>>> type(str()).__name__ # internal python string class.
'str'
Now lets see how the isinstance() works
>>> isinstance(deal, str) # is 'deal' instance of 'str' ?
False
>>> isinstance(deal, Deal) # is 'deal' instance of Deal ?
True
>>>
Posted: January 14th, 2010 | Author: Davo | Filed under: Django | Tags: forms, instance, post, validate | No Comments »
Sometimes it is useful to validate an instance of a model without having the POST values.
You will ask me why? Well, a form can be filled in different steps and be validated at the final step.
This is where it comes handy, validate the Object to see if all the steps are properly completed.
The following example demonstrates how to validate an instance without using the request.POST
from django.db import models
from django import forms
# a simple example of an Article model
class Article(models.Model):
title = models.CharField(max_length=100)
body = models.TextField(max_length=400)
# let's create the form from the Article model.
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
# an article form with only the title on it.
# we can use this as a step 1, where the user is filling only the title.
class ArticleLessform(forms.ModelForm):
class Meta:
model = Article
fields = ('title', ) # only show the title.
# inside views.py
from your_directory.models import Article, ArticleForm, ArticleLessForm
def do_something(request):
# change for the appropriate id.
article_qs = Article.objects.filter(id=1)
# get the actual Article object.
article = article_qs.get()
# all the magic is on this line
# values() returns a key/values pairs and we use this to simulate a request.POST.
form = ArticleForm(article_qs.values()[0], instance=article)
if form.is_valid()
print 'It seems that the title and body are filled properly.'
else:
print 'The Article object did not validate'
You can read more about the values() on the django docs.