I am building a Django app. I have customized the User model. My models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from phonenumber_field.modelfields import PhoneNumberField
from phonenumber_field.phonenumber import PhoneNumber
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, phone_number,username,email=None, password=None):
if not phone_number:
raise ValueError("You must specify your phone number")
if not username:
raise ValueError("You must specify your username")
try:
user = self.model(phone_number= PhoneNumber.from_string(phone_number=phone_number,region="BD").as_national,
username=username,
email=self.normalize_email(email))
except :
user = self.model(phone_number= PhoneNumber.from_string(phone_number=phone_number,region="BD").as_national,
username=username)
user.save(using=self._db)
return user
def create_stuffuser(self, phone_number,username,email,password):
user = self.create_user(phone_number,username,email=email,password=password)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, phone_number,username,email,password):
user = self.create_user(phone_number,username,email=email,password=password)
user.staff = True
user.admin= True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
phone_number = PhoneNumberField(unique=True)
username = models.CharField(unique=False,max_length=50)
REQUIRED_FIELDS = ['username']
email = models.EmailField(unique=False)
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'phone_number'
def get_full_name(self):
return self.username
def get_short_name(self):
return self.username
def get_email(self):
return self.email
def __str__(self):
return str(self.phone_number)
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self,app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
objects = UserManager()
I am logged in but it is throwing error.
My Ticket model:
User = settings.AUTH_USER_MODEL
class Ticket(models.Model):
from_station = models.CharField(max_length=30)
to_station = models.CharField(max_length=30)
purchased_on = models.DateTimeField(default=timezone.now)
travel_on = models.DateTimeField()
customer = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return f"Customer:{self.customer.username},From:{self.from_station},To:{self.to_station},Travel on:{self.travel_on},Purchased on:{self.purchased_on}"
My views.py:
#csrf_protect
#login_required
def buyticket(response):
if response.method == 'POST':
form = Ticket(response.POST)
if form.is_valid():
form.save()
return redirect('main-home-page')
else:
form = Ticket()
return render(response,'main/ticket.html',{'form':form})
The error I got:
Ticket has no customer.
Request Method: GET
Request URL: http://127.0.0.1:8000/ticket/
Django Version: 3.2.4
Exception Type: RelatedObjectDoesNotExist
Exception Value:
Ticket has no customer.
Exception Location: C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in __get__
Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.2
A user can have multiple tickets. But it is not taking any user. Whenever I am trying to go to ticket route it calls me to login. I do but then it throws this error.
This error shows to you cause You declare the from equal to model
in :
else:
form = Ticket()
You should create another file called forms.py in the app
and do something like that
from .models import Ticket
from django.forms import ModelForm
class TicketForm(ModelForm):
class Meta:
model = Ticket
fields = '__all__
and in views
from .forms import TicketForm
def buyticket(response):
form = TicketForm()
if response.method == 'POST':
if form.is_valid():
form.save()
return redirect('main-home-page')
else:
form = TicketForm()
return render(response,'main/ticket.html',{'form':form})
You can get more info in the docs
Related
i'm doing my own project.
the project is signup, signin in django.
i make my own model. not django model.
i use AbstractBaseUser, and create my own model.
this model get name, id, companyname, companycode.
i succeed signup. get name, id, companyname, companycode. and save mysql.
but when i login with this information, always fail.
i think authentication function is error. but i don't know where is the error.
could you help me?
models.py
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, username, userid, company, companycode, password=None):
if not username:
raise ValueError(_('Users must have an name!'))
user = self.model(
username=username,
userid = userid,
company= company,
companycode = companycode,
)
user.save()
return user
def create_superuser(self, username, userid, company, companycode, password):
user = self.create_user(
username=username,
userid = userid,
company = company,
companycode = companycode,
password=password,
)
user.set_password(password)
user.is_superuser = True
user.save()
return user
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=10, unique=True, verbose_name="이름")
userid = models.CharField(max_length=100, unique=True, verbose_name="아이디")
company = models.CharField(max_length=10, verbose_name="회사")
companycode = models.CharField(max_length=100, verbose_name="회사코드")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜")
is_admin = models.BooleanField(default=False)
#is_active = models.BooleanField(default=True)
class Meta:
db_table = 'user'
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['userid', 'company', 'companycode']
def __str__(self):
return self.username
def get_full_name(self):
return self.username
def get_short_name(self):
return self.username
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All superusers are staff
return self.is_superuser
get_full_name.short_description = _('Full name')
backend.py
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from useraccount.models import User
from django.contrib.auth.hashers import check_password
class UseraccountBackend(ModelBackend):
def authenticate(self, request, **kwargs):
username = kwargs['username']
companycode = kwargs['companycode']
try:
useracc = User.objects.get(username=username, companycode=companycode)
if check_password(companycode, kwargs['companycode']) is True:
return useracc.username
'''
if useracc.companycode.check_password(code) is True:
return useracc.username
'''
except User.DoesNotExist:
pass
views.py
def login(request):
if request.method == 'GET':
return render(request, 'useraccount/login.html')
elif request.method == 'POST':
name = request.POST.get('name',None)
code = request.POST.get('code',None)
user = authenticate(username=name, companycode=code)
if user is not None:
login(request, user)
return render(request, 'useraccount/login_success.html')
else:
return render(request, 'useraccount/login_fail.html')
def signup(request):
if request.method == 'GET':
return render(request, 'useraccount/signup.html')
#csrf_exempt
def signup_sign(request): #일반유저 회원가입
if request.method == 'POST':
username = request.POST['name']
userid = request.POST['id']
company = request.POST['company']
code = request.POST['code']
account = User.objects.create_user(
username=username,
userid = userid,
company = company,
companycode = code,
)
#login(request, account)
account.save()
return render(request, 'useraccount/success.html')
I think your first problem is here:
companycode = kwargs['companycode']
[snip]
if check_password(companycode, kwargs['companycode']) is True:
check_password() takes two arguments -- a plaintext password and an encoded password. You are passing the same value for both, so I would not expect that to return True.
(Bonus tip, you don't want to return useracc.username, which would be a string. You want to return useracc which should return a user object.)
I would like to know if it’s possible to create his own login page (from scratch) without using any Django default login forms because I want to add other fields in addition?
Thanks in advance
You could write your own view, but it's better to just subclass the Django LoginView and change as much as you need, for example:
from django.http import HttpResponseRedirect
from django.contrib.auth.views import LoginView
from django.contrib.auth import login
from .forms import MyCustomLoginForm
class SignInView(LoginView):
form_class = MyCustomLoginForm
template_name = 'path/to/my_template.html'
def form_valid(self, form):
# Form is valid, do whatever you need.
login(self.request, form.get_user())
response = HttpResponseRedirect(self.get_success_url())
return response
forms.py
from django import forms
from django.contrib.auth.forms import AuthenticationForm
class MyCustomLoginForm(AuthenticationForm):
age = forms.IntegerField(label='Age', required=True)
def clean_age(self):
age = self.cleaned_data['age']
# validate age
return age
in this user model, I have declared username field as email. User can't get login using username and password. User have to provide email and password to get login.
my models.py
class UserManager(BaseUserManager):
def create_user(self, email, password=None, active=True, is_staff=False, is_admin=False,is_superuser=False):
if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have password")
user_obj = self.model(
email=self.normalize_email(email)
)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = active
user_obj.superuser = is_superuser
user_obj.save(using=self._db)
return user_obj
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_superuser=True,
is_staff=True,
is_admin=True,
)
return user
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
staff = models.BooleanField(default=False)
superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def _str_(self):
return self.email
#property
def is_staff(self):
return self.staff
#property
def is_superuser(self):
return self.superuser
my views.py
from .models import User
class LoginAPIView(APIView):
def post(self, request):
serializer = LoginSerializers(data=request.data)
if serializer.is_valid():
data = serializer.data
email = data['email']
password = data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
token, created = Token.objects.get_or_create(user=user)
return Response({"message": "success", "code": status.HTTP_201_CREATED, "details": serializer.data,
"Token": token.key})
return Response(
{"message": "error", "code": status.HTTP_401_UNAUTHORIZED, "details": ["Invalid credentials"]})
my serializers.py:
class LoginSerializers(serializers.Serializer):
username = serializers.CharField(max_length=255)
password = serializers.CharField(max_length=128)
may be this could help you
I started using cookiecutter-django because it seems so much advanced than just django-admin to start my project. So I created an eCommerce website and it requires only email to log in not the username.
So, I tried to follow the docs and changes my settings.py like this:
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
AUTH_USER_MODEL = 'accounts.User'
LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
Here is my accounts.User model:
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
class UserManager(BaseUserManager):
def create_user(self, email, full_name, password=None, is_active=True, is_staff=False, is_admin=False):
if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have a password")
if not full_name:
raise ValueError("Users must have a fullname")
user_obj = self.model(
email = self.normalize_email(email),
full_name = full_name
)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, email, full_name, password=None):
user = self.create_user(
email,
full_name,
password=password,
is_staff=True
)
return user
def create_superuser(self, email, full_name, password=None):
user = self.create_user(
email,
full_name,
password=password,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['full_name']
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.full_name
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
There is default users dir which has its own models.py, views.py and urls.py but I have no knowledge to modify it.
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.UserListView.as_view(),
name='list'
),
url(
regex=r'^~redirect/$',
view=views.UserRedirectView.as_view(),
name='redirect'
),
url(
regex=r'^(?P<username>[\w.#+-]+)/$',
view=views.UserDetailView.as_view(),
name='detail'
),
url(
regex=r'^~update/$',
view=views.UserUpdateView.as_view(),
name='update'
),
]
models.py:
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
#python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
views.py:
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import User
from enrolments.models import Enrolment
class UserDetailView(LoginRequiredMixin, DetailView):
model = User
# These next two lines tell the view to index lookups by username
slug_field = 'username'
slug_url_kwarg = 'username'
class UserRedirectView(LoginRequiredMixin, RedirectView):
permanent = False
def get_redirect_url(self):
return reverse('users:detail',
kwargs={'username': self.request.user.username})
class UserUpdateView(LoginRequiredMixin, UpdateView):
fields = ['name', ]
# we already imported User in the view code above, remember?
model = User
# send the user back to their own page after a successful update
def get_success_url(self):
return reverse('users:detail',
kwargs={'username': self.request.user.username})
def get_object(self):
# Only get the User record for the user making the request
return User.objects.get(username=self.request.user.username)
class UserListView(LoginRequiredMixin, ListView):
model = User
# These next two lines tell the view to index lookups by username
slug_field = 'username'
slug_url_kwarg = 'username'
Here is the error when I sign in, although it let me sign in when I go to the homepage. but when I click 'Sign In' button it prompts me with this error. Please guide me through it.
Thank you in advance.
As of now (June 2020) there is an easier way to do this with Django Cookie cutter.
Firstly in the Django settings config/settings/base.py we need to adjust the AllAuth settings so that firstly the email is used as the primary identifier and not username, and secondly so that the username field is hidden in the SignUp page
ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
The Django AllAuth documentation of this can be found here
Then in the User model, we add a signal that will fire whenever the user instance is updated and copy the email address over to the username field. This way they stay in sync. The while loop just deals with the situation if there are conflicting email addresses (which their should not be):
#receiver(pre_save, sender=User)
def update_username_from_email(sender, instance, **kwargs):
user_email = instance.email
username = user_email[:130]
n = 1
while User.objects.exclude(pk=instance.pk).filter(username=username).exists():
n += 1
username = user_email[: (129 - len(str(n)))] + "-" + str(n)
instance.username = username
This user model update was proposed by #ferrangb here
Finally, I managed to figure out the way.
Here is my new models.py:
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
class UserManager(BaseUserManager):
def create_user(self, email, username, full_name, password=None, is_active=True, is_staff=False, is_admin=False):
if not email:
raise ValueError("Users must have an email address")
if not password:
raise ValueError("Users must have a password")
if not full_name:
raise ValueError("Users must have a fullname")
user_obj = self.model(
email = self.normalize_email(email),
full_name = full_name,
username = new_username
)
user_obj.set_password(password)
user_obj.staff = is_staff
user_obj.admin = is_admin
user_obj.active = is_active
user_obj.save(using=self._db)
return user_obj
def create_staffuser(self, username, email, full_name, password=None):
user = self.create_user(
email,
full_name,
username=username,
password=password,
is_staff=True
)
return user
def create_superuser(self, username, email, full_name, password=None):
user = self.create_user(
email,
full_name,
username=username,
password=password,
is_staff=True,
is_admin=True
)
return user
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
full_name = models.CharField(max_length=255, blank=True, null=True)
username = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['full_name']
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.full_name
def get_short_name(self):
return self.email
def get_username(self):
return self.username
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.active
Here is my views.py file in 'users' dir:
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from accounts.models import User
from enrolments.models import Enrolment
class UserDetailView(LoginRequiredMixin, DetailView):
model = User
# These next two lines tell the view to index lookups by username
slug_field = 'username'
slug_url_kwarg = 'username'
class UserRedirectView(LoginRequiredMixin, RedirectView):
permanent = False
def get_redirect_url(self):
return reverse('users:detail',
kwargs={'username': self.request.user.username})
class UserUpdateView(LoginRequiredMixin, UpdateView):
fields = ['full_name', ]
# we already imported User in the view code above, remember?
model = User
# send the user back to their own page after a successful update
def get_success_url(self):
return reverse('users:detail',
kwargs={'username': self.request.user.username})
def get_object(self):
# Only get the User record for the user making the request
return User.objects.get(username=self.request.user.username)
class UserListView(LoginRequiredMixin, ListView):
model = User
# These next two lines tell the view to index lookups by username
slug_field = 'username'
slug_url_kwarg = 'username'
and my settings.py file:
# ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
# ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
AUTH_USER_MODEL = 'accounts.User'
LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
Although, I need to have username while signing up only but after that, it just works. I don't need to change any other files.
I hope this helps.
Thanks.
I'm trying to create a new user in my Django app but nothing happens. I'm using a custom user auth model. Part of the code I edited from the docs. Why the error message "Users must have an email address" is reported by the model and not the forms? Why am I not able to create a user? I don't get any error back.
My model:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.utils import timezone
class MyUserManager(BaseUserManager):
def create_user(self, email, name, neighborhood, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
neighborhood=neighborhood
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, neighborhood, password):
user = self.create_user(
email=email,
name=name,
password=password,
neighborhood=neighborhood
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
name = models.CharField(max_length=255)
email = models.EmailField(max_length=255, unique=True)
created_at = models.DateTimeField(default=timezone.now, blank=True)
neighborhood = models.CharField(max_length=255)
consultant_id = models.IntegerField(null=True)
moip_id = models.IntegerField(null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name', 'neighborhood']
def __str__(self):
return self.name
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
My form:
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from dashboard.models import MyUser
class UserCreationForm(forms.ModelForm):
password = forms.CharField(label='Senha', widget=forms.PasswordInput)
confirm_password = forms.CharField(label='Confirmar senha', widget=forms.PasswordInput)
class Meta:
model = MyUser
# Note - include all *required* MyUser fields here,
# but don't need to include password and confirm_password as they are
# already included since they are defined above.
fields = ('email', 'name', 'neighborhood',)
def clean(self):
cleaned_data = super(UserCreationForm, self).clean()
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
if password and confirm_password and password != confirm_password:
raise forms.ValidationError('As senhas nao batem.')
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password'])
if commit:
user.save()
return user
And my view:
from django.shortcuts import render
from frontend.forms import UserCreationForm
# Create your views here.
def register(request):
message = None
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'frontend/register.html', {'message': message})
So far I know, you do not raise error from forms, you just -
1) add the error in it, then it automatically gets invalided by django and is posted back with error and also
2) since you are overriding the clean method you must return the cleaned data. So change the clean method with these details -
def clean(self):
cleaned_data = self.cleaned_data
password = cleaned_data.get('password')
confirm_password = cleaned_data.get('confirm_password')
if password and confirm_password and password != confirm_password:
#raise forms.ValidationError('As senhas nao batem.') => we do not raise error in form clean, instead we add it in validation error.
self.add_error('confirm_password', 'As senhas nao batem.')
return super(UserCreationForm, self).clean() # =>this line is IMPORTANT to not break the calling hierarchy
a little shorter -
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
self.add_error('confirm_password', 'Password & Confirm Password must match.')
return super().clean()
Sine you are not returning anything, the cleaned_data of your form is empty and thus django is returning you back to the form page with no data in it.
I have a Post model with OneToOneField to a User model
class Post(models.Model):
user = models.OneToOneField(User)
title = models.CharField(max_length=255)
content = models.TextField()
date = models.DateField(auto_now_add = True)
def __unicode__(self):
return self.title
When I add a new post (using forms), everything is OK. But when I add the second post passing the same user, I get the UNIQUE constraint failed: socnet_post.user_id error.
I use a custom authentication backend:
from django.contrib.auth.models import User
class EmailAuthBackend(object):
def authenticate(self, username=None, password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Exception goes from the post.save() line:
#login_required
def profile(request, username=None):
context = RequestContext(request)
if not username:
username = request.user.username
user = User.objects.get(username=username)
posts = Post.objects.filter(user=user)
context_dict = {'posts': posts}
if request.method == 'POST':
form = AddPostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
add_post_form = AddPostForm()
context_dict['add_post_form'] = add_post_form
return render_to_response('socnet/profile.html', context_dict, context)
It looks like you should use a foreign key instead of the one-to-one field as it's a one-to-many relationship (user can write many articles):
class Post(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=255)
content = models.TextField()
date = models.DateField(auto_now_add = True)
def __unicode__(self):
return self.title