How to import datetime module in Django? - 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

Related

AUTH_USER_MODEL refers to model 'base.User' that has not been installed for custom auth backend

I'm trying to customize auth backend while customized auth model but keep facing this error because i'm using get_user_model() function.
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'base.User' that has not been installed
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base.apps.BaseConfig',
'core.apps.AccountsConfig',
'system.apps.SystemConfig',
]
custom Backend:
class UserBackend(object):
def authenticate(self, request, username=None, password=None, **kwargs):
usermodel = User
try:
usr = usermodel.objects.get(username=username)
password_valid = usr.check_password(password)
if usr and password_valid:
return usr
raise PermissionDenied
except usermodel.DoesNotExist:
return PermissionDenied
return None
def get_user(self, user_id):
usermodel = User
try:
return usermodel.objects.get(pk=user_id)
except usermodel.DoesNotExist:
return None
Edit:
settings:
AUTH_USER_MODEL = 'base.User'
AUTHENTICATION_BACKENDS = (
'base.models.UserBackend',
)
base.User model:
class User(AbstractUser):
fullname = models.CharField(max_length=35, null=True, blank=True)
picture = models.ManyToManyField('ImageFile', verbose_name="ProfilePicture", blank=True)
bio = models.CharField(max_length=255, null=True, blank=True)
link = models.URLField(null=True, blank=True, default="")
is_private = models.BooleanField(default=False)
is_official = models.BooleanField(default=False)
Note: UserBackend is on the end of file and class User(AbstractUser) is above it
There was an import in base.models file, from django.contrib.auth.backends import ModelBackend which caused this error even when i removed custom AUTHENTICATION_BACKENDS.after i removed this import, everything works fine although i moved backend class from base.models to backend file in the base app (i think its not necessary, i just did it for more readable codes)
For me it was the same. It took me over an hour to find out that you cannot have the CustomBackend(BaseBackend) and the CustomUser(AbstractUser) in the models.py of your app. This info is nowhere to be found in the official Django docs.
Django Version: 3.1.2
Python Version: 3.8.2
models.py of the app "Users":
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
auth.py (arbitrary name, living in the "Users" app):
from django.db import models
from django.contrib.auth.backends import BaseBackend
class UserAuth(BaseBackend):
def authenticate(self, request, username, password):
pass
def get_user(self, user_id):
pass
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig'
]
AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = [
'users.auth.UserAuth'
]

Django: ModelForm doesn't submmit

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

Module 'django.db.models' has no attribute 'FileBrowseField'

I would like to have on my Django 2.1.1 site django-filebrowser-no-grappelli. I've followed this indications but at the end of the procedure, when I restart my server, I've this error:
header_image = models.FileBrowseField("Image", max_length=200,
directory="images/", extensions=[".jpg"], blank=True) AttributeError:
module 'django.db.models' has no attribute 'FileBrowseField'
This are the files of my project:
MODELS.PY
from django.db import models
from django.urls import reverse
from tinymce import HTMLField
from filebrowser.fields import FileBrowseField
class Post(models.Model):
"""definizione delle caratteristiche di un post"""
title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True)
short_description = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo")
contents = HTMLField(help_text="Write your post here", verbose_name="Contenuti")
publishing_date = models.DateTimeField(verbose_name="Data di pubblicazione")
updating_date = models.DateTimeField(auto_now=True, verbose_name="Data di aggiornamento")
header_image = models.FileBrowseField("Image", max_length=200, directory="images/", extensions=[".jpg"], blank=True)
slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("singlearticleView", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
VIEWS.PY
from django.shortcuts import render
from .models import Post
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
class SingleArticle(DetailView):
model = Post
template_name = "single_article.html"
class ListArticles(ListView):
model = Post
template_name = "list_articles.html"
def get_queryset(self):
return Post.objects.order_by('-publishing_date')
URLS.PY
from django.urls import path
from .views import ListArticles, SingleArticle
urlpatterns = [
path("", ListArticles.as_view(), name="listarticlesView"),
path("<slug:slug>/", SingleArticle.as_view(), name="singlearticleView"),
]
ADMIN.PY
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
"""creazione delle caratteristiche dei post leggibili nel pannello di amministrazione"""
list_display = ["title", "publishing_date", "updating_date", "id"]
list_filter = ["publishing_date"]
search_fields = ["title", "short_description", "contents"]
prepopulated_fields = {"slug": ("title",)}
fieldsets = [
(None, {"fields": ["title", "slug"]}),
("Contenuti", {"fields": ["short_description", "contents"]}),
("Riferimenti", {"fields": ["publishing_date"]}),
]
class Meta:
model = Post
admin.site.register(Post, PostAdmin)
URLS.PY PROJECT
from django.contrib import admin
from django.urls import path, include
from filebrowser.sites import site
urlpatterns = [
path('admin/filebrowser/', site.urls),
path('grappelli/', include('grappelli.urls')),
path('admin/', admin.site.urls),
path('', include('app4test.urls')),
path('tinymce/', include('tinymce.urls')),
]
I've started all of this because I will use TinyMCE and a file browser application is necessary. When I deactive the string header_image in models.py the project running well but, obviously, when I try to upload an image I've an error.
Where I made a mistake?
your import is done like this:
from filebrowser.fields import FileBrowseField
but you're trying to use the field following way:
header_image = models.FileBrowseField(...)
It's not part of the models package, just do it without the models. part:
header_image = FileBrowseField(...)

Django Haystack + ElasticSearch Implementation on Windows OS env

I am developing a project with HayStack+ElasticSearch for search engine and I am having hard time to get around it. I've setup models and Inexing for the models as shown below:
models.py:
from django.db import models
from django.core.urlresolvers import reverse
class Product(models.Model):
title = models.CharField(max_length=500)
description = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to='products/')
price = models.DecimalField(max_digits=20, decimal_places=2)
sku = models.CharField(null=True, max_length=100)
url = models.URLField(blank=True)
displayed_category = models.CharField(null=True, max_length=500)
categories = models.ManyToManyField('Category', blank=True)
default = models.ForeignKey(
'Category', related_name='default_category', null=True, blank=True
)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
class Category(models.Model):
title = models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique=True)
description = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
Views.py:
from datetime import date
from .models import Product
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.core.paginator import Paginator
from haystack.generic_views import SearchView
class ProductListView(ListView):
model = Product
paginate_by = 10
class ProductDetailView(DetailView):
model = Product
class ProductSearchView(SearchView):
model = Product
def get_queryset(self):
queryset = super(ProductSearchView, self).get_queryset()
# further filter queryset based on some set of criteria
return queryset
def get_context_data(self, *args, **kwargs):
context = super(ProductSearchView, self).get_context_data(*args, **kwargs)
context["query"] = self.request.GET.get("q")
return context
search_index.py:
from haystack import indexes
from .models import Product
class TweetIndex(indexes.SearchIndex, indexes.Indexable):
title = indexes.CharField(model_attr='title')
text = indexes.EdgeNgramField(model_attr='text', document=True, use_template=True)
def prepare_title(self, obj):
return obj.title or ''
def get_model(self):
return Product
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from products.views import ProductSearchView
urlpatterns = [
url(r'^$', 'shopsy.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^products/', include('products.urls')),
url(r'^search/', ProductSearchView.as_view()),
url(r'search/$', include('haystack.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
App urls.py:
from django.conf.urls import url
from .views import ProductListView, ProductDetailView, ProductSearchView
urlpatterns = [
url(r'^$', ProductListView.as_view(), name='products'),
url(r'^(?P<pk>\d+)/$', ProductDetailView.as_view(), name='product_detail'),
]
settings.py:
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
INTERNAL_IPS = ('127.0.0.1',)
With all the above settings when I run "manage.py rebuild_index" I get the following error.
Removing all documents from your index because you said so.
Failed to clear Elasticsearch index: ConnectionError(<urllib3.connection.HTTPCon
nection object at 0x03C12850>: Failed to establish a new connection: [Errno 1006
1] No connection could be made because the target machine actively refused it) c
aused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x03C1
2850>: Failed to establish a new connection: [Errno 10061] No connection could b
e made because the target machine actively refused it)
Traceback (most recent call last):
File "C:\Users\Shazia\Desktop\working directtory\searchEngin\lib\site-packa
ges\haystack\backends\elasticsearch_backend.py", line 234, in clear
self.conn.indices.delete(index=self.index_name, ignore=404)
File "C:\Users\Shazia\Desktop\working directtory\searchEngin\lib\site-packa
ges\elasticsearch\client\utils.py", line 69, in _wrapped
return func(*args, params=params, **kwargs)
File "C:\Users\Shazia\Desktop\working directtory\searchEngin\lib\site-packa
ges\elasticsearch\client\indices.py", line 198, in delete
params=params)
Please advise if I am doing something or all the way wrong.
If the ES server is not responding it could be for several reasons:
The ES server is not started
The ES server is not configured to listen on localhost or 127.0.0.1
The ES server is not installed at all.
In your case, it was the third option. You just need to install Elasticsearch as explained in the Django Haystack docs, start it and then it will work.

FieldError — Unknown field(s): django-fluent-contents

I'm a Python/Django noob. So any help will be appreciated.
Trying to use the django-fluent-contents
models.py
from django.core.urlresolvers import reverse
from django.db import models
from fluent_contents.models.fields import PlaceholderField, PlaceholderRelation, ContentItemRelation
from fluent_contents.models import ContentItem
class Article(models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField("Slug", unique=True)
content = PlaceholderField("article_content")
placeholder_set = PlaceholderRelation()
contentitem_set = ContentItemRelation()
class Meta:
verbose_name = "Article"
verbose_name_plural = "Articles"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('article-details', kwargs={'slug': self.slug})
admin.py
from django.contrib import admin
from article.models import Article
from fluent_contents.admin import PlaceholderFieldAdmin
class ArticleAdmin(PlaceholderFieldAdmin):
prepopulated_fields = {'slug': ('title',)}
fieldsets = (
(None, {
'fields': ('title', 'slug', ),
}),
("Contents", {
'fields': ('content',),
'classes': ('plugin-holder',),
})
)
admin.site.register(Article, ArticleAdmin)
I'm using South for migration.
db.create_table(u'article_article', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=200)),
('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=50)),
))
db.send_create_signal(u'article', ['Article'])
It looks like, no column is being created for the 'content' field.
So when I try to add a new 'Article' via django admin —
FieldError at /manage/article/article/add/
Unknown field(s) (content) specified for Article. Check fields/fieldsets/exclude attributes of class ArticleAdmin.
If I remove the fieldset from admin.py
class ArticleAdmin(PlaceholderFieldAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Article, ArticleAdmin)
The 'content' field is not shown in django admin
In reply to #vdboor.. Here's my installed apps ...
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
# 3rd party apps
'south',
'django_extensions',
'compressor',
'debug_toolbar',
'fluent_contents',
'fluent_contents.plugins.text',
'django_wysiwyg',
# Project specific apps go here
'article',
)
Also I'm using the example app from the repo as a guide... just removed the extra plugin model
FYI I'm using
Django==1.6
MySQL-python==1.2.4
South==0.8.4
Thank you for all the help :-)
It looks like, no column is being created for the 'content' field.
That is correct, the PlaceholderField becomes a reverse-generic-relation.
You can try removing the fieldsets declaration for now, and see what other error you get.
The repository also contains an example application, which you can run, and compare with your app.
Silly question, but is fluent_contents in the INSTALLED_APPS?
Still need to add extra fields. In the example shown, because the content is stored in a separate table - model ContentItem.
from fluent_contents.models.fields import PlaceholderField, PlaceholderRelation, ContentItemRelation
class Article(models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField("Slug", unique=True)
content = PlaceholderField("article_content")
placeholder_set = PlaceholderRelation() # <-- this
contentitem_set = ContentItemRelation() # <-- and this
class Meta:
verbose_name = "Article"
verbose_name_plural = "Articles"