Django: ModelForm doesn't submmit - django

I've a 2 steps form. Actually these are 2 forms. The first one lets me capture size and quantity variables from rendered ChoiceFields and save them in session.
2nd Form: renders a FileField and a CharField; and on submit is supposed to retrieve the size and quantity stored in session.
So at the end I'm submitting a record of SizeQuantity model with 5 fields: product (ForeignKey to Product model), size, quantity, image (making this optional - null True / blank True to discard its causing any troubles), comment (optional).
However, my when I click on the form submit button, on StepTwoForm (2nd form and final) my form doesn't submit -and therefore does not save a record in DB, I don't see any entering by the admin (model is registered).
The page just stays there, and the if image is uploaded this field gets empty in the html.
models.py
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='category', blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('shop:products_by_category', args=[self.slug])
def __str__(self):
return '{}'.format(self.name)
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='product', blank=True)
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_url(self):
return reverse('shop:ProdCatDetail', args=[self.category.slug, self.slug])
def __str__(self):
return '{}'.format(self.name)
class SizeQuantity(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
size = models.CharField(max_length=10, choices=TAMANIOS)
quantity = models.CharField(max_length=10, choices=CANTIDADES)
image = models.ImageField(upload_to='images', blank=True, null=True)
# imagenes = models.ImageField(upload_to='category', blank=True)
comment = models.CharField(max_length=200, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.size
views.py
# Tamanos y cantidades
class StepOneView(FormView):
form_class = StepOneForm
template_name = 'shop/product.html'
success_url = 'shop/subir-arte'
def get_initials(self):
# pre-populate form if someone goes back and forth between forms
initial = super(StepOneView, self).get_initial()
initial['size'] = self.request.session.get('size', None)
initial['quantity'] = self.request.session.get('quantity', None)
initial['product'] = Product.objects.get(
category__slug=self.kwargs['c_slug'],
slug=self.kwargs['product_slug']
)
return initial
# pre-populate form if someone goes back and forth between forms
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['product'] = Product.objects.get(
category__slug=self.kwargs['c_slug'],
slug=self.kwargs['product_slug']
)
return context
def form_valid(self, form):
# In form_valid method we can access the form data in dict format
# and will store it in django session
self.request.session['product'] = form.cleaned_data.get('product')
self.request.session['size'] = form.cleaned_data.get('size')
self.request.session['quantity'] = form.cleaned_data.get('quantity')
return HttpResponseRedirect(self.get_success_url())
# here we are going to use CreateView to save the Third step ModelForm
class StepTwoView(CreateView):
form_class = StepTwoForm
template_name = 'shop/subir-arte.html'
success_url = '/'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['product'] = Product.objects.get(
category__slug=self.kwargs['c_slug'],
slug=self.kwargs['product_slug']
)
return context
def form_valid(self, form):
# form.instance.product = Product.objects.get(
# category__slug=self.kwargs['c_slug'],
# slug=self.kwargs['product_slug']
# )
form.instance.product = self.request.session.get('product') # get tamanios from session
form.instance.size = self.request.session.get('size') # get tamanios from session
form.instance.quantity = self.request.session.get('quantity') # get cantidades from session
del self.request.session['product']
del self.request.session['quantity'] # delete cantidades value from session
del self.request.session['size'] # delete tamanios value from session
self.request.session.modified = True
return super(StepTwoView, self).form_valid(form)
forms.py:
class StepOneForm(forms.Form):
size = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño')
quantity = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad')
class StepTwoForm(forms.ModelForm):
instructions = forms.CharField(widget=forms.Textarea)
class Meta:
model = SizeQuantity
fields = ('image', 'comment')
def __init__(self, *args, **kwargs):
super(StepTwoForm, self).__init__(*args, **kwargs)
self.fields['comment'].required = False
self.fields['image'].required = False
def save(self, commit=True):
instance = super(StepTwoForm, self).save(commit=commit)
# self.send_email()
return instance
urls.py
urlpatterns = [
path('', views.allProdCat, name = 'allProdCat'),
path('<slug:c_slug>', views.allProdCat, name = 'products_by_category'),
path('<slug:c_slug>/<slug:product_slug>/medida-y-cantidad', views.StepOneView.as_view(), name='ProdCatDetail'),
path('<slug:c_slug>/<slug:product_slug>/subir-arte', views.StepTwoView.as_view(), name='UploadArt'),
]
subir-arte.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
{{ form.image|as_crispy_field }}
<div id="instrucciones-adicionales" style="display: none">
<p class="bold-font"> Instrucciones adicionales (opcional):</p>
{{ form.comment|as_crispy_field }}
</div>
</div>
</br>
</br>
<p>O, sáltate este paso y envía tu arte por correo electrónico</p>
<button type="submit" class="btn btn-naranja text-white btn-block">Continuar
</button>
</form>
project settings file:
"""
Django settings for perfectcushion project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf#)zq-rbxe9z'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shop',
'search_app',
'cart',
'stripe',
'order',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'perfectcushion.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'shop', 'templates/'),
os.path.join(BASE_DIR, 'search_app', 'templates/'),
os.path.join(BASE_DIR, 'cart', 'templates/'),
os.path.join(BASE_DIR, 'order', 'templates/'),]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'shop.context_processor.menu_links',
'cart.context_processor.counter'
],
},
},
]
WSGI_APPLICATION = 'perfectcushion.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
### Stripe Settings ###
CRISPY_TEMPLATE_PACK = 'bootstrap4'

In your get_initials function ,
def get_initials(self):
# pre-populate form if someone goes back and forth between forms
initial = super(StepOneView, self).get_initials() #mispelled
You have mispelled the function call in the super

Related

Django Rest Framework - return Response(serializer.data) image field get null instead of the url

I set an 'ImageField' in the model, using postman to post data. The image uploaded successfully. However, when my view returns serializers.data, the image field is null, which is supposed to be the URL of the image. Does anyone have any ideas? I appreciate it so much.
This is the response
{
"user": 7,
"category": "2018",
"cover": null,
"name": "Louisville"
}
This is my model
class Journey(models.Model):
def user_directory_path(self, filename):
return 'media/journey_cover/{0}/{1}'.format(self.user_id, filename)
user = models.ForeignKey(to=UserProfile, related_name="journeys", on_delete=models.CASCADE)
category = models.CharField(null=False, max_length=50)
cover = models.ImageField(upload_to=user_directory_path)
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(null=False, max_length=50)
My serializer:
class JourneySerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(queryset=UserProfile.objects.all())
cover = serializers.ImageField(use_url=True)
class Meta:
model = Journey
fields = ['user', 'category', 'cover', 'name']
My View
class JourneyList(APIView):
permission_classes = [IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly]
parser_classes = [MultiPartParser, FormParser]
def post(self, request):
print(request.content_type)
serializer = JourneySerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
journey = serializer.create(serializer.validated_data)
journey.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
in the url.py file you have to add
from django.conf.urls.static import static
urlpatterns = [
..... // your urls
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
and in the setting file
STATIC_URL = 'static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

django - custom_user : How to make and EditProfile view?

I've installed django-registration-redux and custom_user. I have a UserProfile model with fullname,dob and photo as extra fields.
I have connected the UserProfile with user-registration so as to save the additional fields to UserProfile table.
Here my questions are...
How do I validate fields in UserProfile model at the time of registration so that I can prevent addition of a user to the emailuser table. Say, if the dob given is invalid or not in allowed range, then stop adding a user to emailuser table.
How can I make an EditProfile system that allows authenticated users to edit their profile (/user/edit - id to be obtained from session).
Below is my settings.py file
INSTALLED_APPS = [
'django.contrib.admin',
'custom_user',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
#------------
'registration',
'userprofile',
]
AUTH_USER_MODEL = 'custom_user.EmailUser'
models.py
class UserProfile(models.Model):
user=models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
primary_key=True,)
fullname=models.CharField(max_length=70, blank=False)
dob=models.DateField(blank=False)
photo=models.ImageField(upload_to='profile_images', blank=False)
def __str__(self):
return self.user.email
def user_registered_callback(sender, user, request, **kwargs):
profile = UserProfile(user = user)
profile.fullname =request.POST["fullname"]
profile.dob ="%s-%s-%s" % (request.POST["dob_year"],request.POST["dob_month"],request.POST["dob_day"])
if 'photo' in request.FILES:
profile.photo = request.FILES['photo']
profile.save()
user_registered.connect(user_registered_callback)
forms.py
class UserProfileForm(RegistrationForm):
fullname=forms.CharField(required=True,label="Full name", min_length=3, max_length=75)
dob=forms.DateField(required=True,label="Date of birth",
widget=forms.SelectDateWidget(years=range(now.year-settings.AGE_UPPER,now.year-settings.AGE_LOWER)))
photo=forms.ImageField(required=False)
views.py
def profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/user/login')
else:
return render(request, 'userprofile/profile.html', {"user":request.user})
class EditProfile(UpdateView):
template_name = 'userprofile/edit_profile.html'
fields = ['fullname','dob','photo']
main urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'user/register/$',
RegistrationView.as_view(form_class = UserProfileForm),
name = 'registration_register'),
url(r'^user/', include('registration.backends.default.urls')),
url(r'^user/', include('userprofile.urls')),
userprofile.urls.py
urlpatterns = [
url(r'^profile/$', views.profile, name='profile'),
url(r'^profile/edit/$', views.EditProfile.as_view(), name='edit_profile'),
]
Right now I'm, getting EditProfile is missing a QuerySet. Define EditProfile.model, EditProfile.queryset, or override EditProfile.get_queryset().
Is it the right way to proceed? Any help would be appreciated.
Thanks

Django Uploaded images not displayed in development

I have defined a model with a 'pic' image field:
class Photo(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
teaser = models.TextField('teaser', blank=True)
pic = models.ImageField(upload_to = 'pic_folder/', default = 'pic_folder/None/default.jpg')
created=models.DateTimeField(default=datetime.datetime.now)
pub_date=models.DateTimeField(default=datetime.datetime.now)
categories = models.ManyToManyField(Category, blank=True)
likes = models.IntegerField(default=0)
dislikes = models.IntegerField(default=0)
visits = models.IntegerField(default=0)
slug = models.CharField(max_length=100, unique=True, blank=True)
And here is the upload form:
class PhotoForm(forms.ModelForm):
class Meta:
model= Photo
fields = ( 'title', 'pic','body', 'categories')
Wich post to this view:
#staff_member_required
def add_photo(request):
if request.method == 'POST':
form = PhotoForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.info(request, "photo was added")
return render(request, 'home.html')
else:
messages.info(request, 'form not valid')
return render(request, 'home.html')
if request.method == 'GET':
form = PhotoForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render(request, 'photo/add_photo.html', args)
The problem is that while photo objects are being saved and the file uploaded but the images are not displayed.
<div class="photo_body"><img src="pic_folder/someimage.jpg" ></div>
I also set
MEDIA_ROOT = '/path/to/my_project/pic_folder'
and run manage.py collectstatic, but they did not solve the problem.
I really got confused about this. So appreciate your hints.
First of all make a folder called media in your project's directory.
Django will store all your uploaded images inside media/pic_folder/ automatically.
In your settings.py file, add this:
MEDIA_URL = '/media/'
MEDIA_ROOT = '/path_to/media/' # write the path to the media folder you just created.
In your urls.py file, add the following lines at the top:
from django.conf import settings
from django.conf.urls.static import static
and add the following line at the end:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
something like below:
urlpatterns = patterns('',
# Your urls here
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And, finally, in your templates:
<img src="{{MEDIA_URL}}pic_folder/someimage.jpg" />

Django Error Page not found (404)

I'm been working on this Photo Organizer and Sharing App Part I at http://lightbird.net/dbe/photo.html. I'm trying to add a picture and when I do . I get this error.
Page not found (404)
Request Method: GET
Request URL: http://donkey123.pythonanywhere.com/admin/photo/image/1/images/Penguins_7.jpg/
image object with primary key u'1/images/Penguins_7.jpg' does not exist.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
My Models is
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from string import join
import os
from PIL import Image as PImage
from mysite.settings import MEDIA_ROOT
class Album(models.Model):
title = models.CharField(max_length=60)
public = models.BooleanField(default=False)
def __unicode__(self):
return self.title
class Tag(models.Model):
tag = models.CharField(max_length=50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length=60, blank=True, null=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
def __unicode__(self):
return self.image.name
def save(self, *args, **kwargs):
"""Save image dimensions."""
super(Image, self).save(*args, **kwargs)
im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
self.width, self.height = im.size
super(Image, self).save(*args, ** kwargs)
def size(self):
"""Image size."""
return "%s x %s" % (self.width, self.height)
def __unicode__(self):
return self.image.name
def tags_(self):
lst = [x[1] for x in self.tags.values_list()]
return str(join(lst, ', '))
def albums_(self):
lst = [x[1] for x in self.albums.values_list()]
return str(join(lst, ', '))
def thumbnail(self):
return """<img border="0" alt="" src="/media/%s" height="40" />""" % (
(self.image.name, self.image.name))
thumbnail.allow_tags = True
class AlbumAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["title"]
class TagAdmin(admin.ModelAdmin):
list_display = ["tag"]
class ImageAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["__unicode__", "title", "user", "rating", "size", "tags_", "albums_","thumbnail","created"]
list_filter = ["tags", "albums","user"]
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
I think My Models,py is fine but I think the problem lay at the
MEDIA_ROOT= and MEDIA URL=
My MEDIA_ROOT = '/home/donkey123/mysite/photo'
and my MEDIA_URL is "" which is blank.
I don't know what to put for my MEDIA_URL which is the problem.
Thanks in advance
In your model (note there is no need for the slash at the end):
image = models.FileField(upload_to="images")
That means these images will go in {media folder}/images/
In settings.py:
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '../../web/media').replace('\\','/')
That means the media folder is: project_root/web/media
So the images from this model will go in: project_root/web/media/images
The stuffs above define where the images are saved on the filesystems. Now what you want to do is to define where they will be accessed via HTTP.
In settings.py define the url pointing to the media folder:
MEDIA_URL = '/media/'
Then the images from this model will be in:
http://my-url/media/images/image_name.jpg
Tests these settings without your model/library first with one image. Then read the following:
To reply to your specific questions:
My MEDIA_ROOT = '/home/donkey123/mystic/photo' => see my example, the MEDIA_ROOT should be relative to your settings.py file so it will work when going live, on another dev machine, etc.
and my MEDIA_URL= is "" which is blank. => that should be '/media/' because in the model you are doing this:
def thumbnail(self):
return """<a href="/media/%s">
Hope that helps
settings.py
import os
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..')
SITE_ROOT = PROJECT_ROOT
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
Problem is with the regular expression in your urls.py, which is taking everything after 1 and passing it in as the primary key.
I think, When any web page is removed or moved then 404 happens. Otherwise your hosting provider is not good.

How to import datetime module in Django?

I've learned some basic in Django but I stucked in this tutorial:
http://docs.djangoproject.com/en/dev/intro/tutorial02/#customize-the-admin-change-list
Error found when was_published_today added:
global name 'datetime' is not defined
Some search results suggest me to import datetime module, but I have no idea how to do it.
from django.db import datetime in polls/admin.py or polls/models.py seems useless
This is settings.py:
# Django settings for kaka project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'kaka' # Or path to database file if using sqlite3.
DATABASE_USER = 'root' # Not used with sqlite3.
DATABASE_PASSWORD = 'z' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '5vqk*i^#8%=nkhy46z9uf7vx#5g*0e6#uons*+gb^iakgg8y$('
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'kaka.urls'
TEMPLATE_DIRS = (
"/var/mycode/cina", # Change this to your own directory.
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'kaka.polls',
'django.contrib.admin'
)
This is polls/models.py:
from django.db import models
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
question = models.CharField(max_length=200)
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
was_published_today.short_description = 'Published today?'
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
This is polls/admin.py:
from kaka.polls.models import Poll
from kaka.polls.models import Choice
from django.contrib import admin
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
list_display = ('question', 'pub_date', 'was_published_today')
inlines = [ChoiceInline]
list_filter = ['pub_date']
search_fields = ['question']
date_hierarchy = 'pub_date'
admin.site.register(Poll, PollAdmin)
admin.site.register(Choice)
I needed to import the timezone module in polls/models.py
from django.utils import timezone
in my version of django/python datetime doesn't provide timezone support
In polls/models.py you need to add import datetime in the same manner as from django.db import models.
from django.db import models
import datetime # < add it here
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
question = models.CharField(max_length=200)
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
was_published_today.short_description = 'Published today?'
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
You can try to add this , import datetime can be able to could'nt work :
from datetime import datetime
Couldn't add this in formatted text to #zack's answer, but it would look like:
polls/models.py
from django.db import models
import datetime
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
import datetime