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.
Related
I have problem with django request.I dont know. I tried to do everything, but I got
'blog' object has no attribute 'get'. I want to do mini blog on my website,but it isnt working now. I would like to get all objects from database.(Sorry,If I did something wrong,I am beginner in django and tried to functions for my website) :)
models.py
from django.db import models
# Create your models here.
CHOOSE =[
('Usual','Обычный тариф'),
('Premium','Премиум тариф'),
('Prise','Аукционный')
]
class VDSTARIFS( models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
name = models.CharField(max_length=20, verbose_name = 'Цены')
choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
title = models.CharField(max_length= 15)
def __str__(self):
return str(self.title)
class blog(models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
message = models.TextField( verbose_name= 'Сообщение блога')
titleblog = models.CharField(max_length=50, verbose_name = 'Название')
img = models.ImageField(upload_to = 'admin/', verbose_name= 'Картинка' )
def __str__(self):
return str(self.titleblog)
def get_all_objects(self): ##maybe I have troubles with it.
queryset = self.__class__.objects.all()
blog.html
{% csrftoken %}
{% for item in message %}
{% endfor %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponseRedirect
import os
from polls.models import VDSTARIFS
from polls.models import blog
from django.template.loader import render_to_string
def index_view(request):
#return HttpResponse("<h1>Hello</h1>")
return render(request, "home.html", {})
def about(request):
return render(request, "about.html", {})
def minecraft(request):
return render(request, "minecraft.html",{})
def vds(request):
HTML_STRING = render_to_string("vds.html", context = context1)
return HttpResponse(HTML_STRING)
try:
VDS1 = VDSTARIFS.objects.get(id=0)
name = VDS1.name
except VDSTARIFS.DoesNotExist:
VDS1 = None
context1 = {
'name':name,
'prise':VDS1,
}
def messagesblog(request,self):
HTML_STRING = render_to_string('blog.html')
return HttpResponse(HTML_STRING)
urls.py
from django.contrib import admin
from django.urls import path
from polls import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index_view, name='home'),
path('vds', views.vds, name='vds' ),
path('minecraft', views.minecraft, name='minecraft' ),
path('about', views.about, name='about'),
path('blog', views.blog, name='blog')
]
The actual error is probably caused by the wrong url pattern:
path('blog', views.blog, name='blog')
views.blog refers to the blog model due to:
from polls.models import blog
What you need here is the view not the model, so:
path('blog', views.messagesblog, name='blog')
Then, remove the "self" argument from your messagesblog function.
Use the "render" function from django.shortcuts and provide a context with the blog objects:
def messagesblog(request):
return render(request, "blog.html", {message: blog.objects.all()})
That might solve your problem.
Still, there are some things you could improve.
E.g.: Don't use "id" fields in your model definitions if you don't really, really have to, as this is usually an auto-generated number (BigInt) field.
That's only one tip from an old Django veteran happy to be finally heard. You'll find out much more yourself as you proceed.
#project url
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
import products
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('products.urls')),
url(r'^product/(?P<title>[\w-]+)/$', products.views.single,name='single')
]
# app url
from django.urls import path, include
import products
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
#model
class products(models.Model):
title = models.CharField(max_length=120)
desc = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2, default=29.99)
sales_price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=False, default=0)
slug = models.SlugField(unique=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
update = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
def get_price(self):
return self.price
def get_absolute_url(self):
return reverse("single", kwargs={"title": self.title})
#views
def home(request):
product = products.objects.all()
template = 'home.html'
context = {'product': product}
return render(request, template, context)
def single(request,title):
try:
product = products.objects.get(title=title)
template = 'products.html'
context = {'product': product}
return render(request, template, context)
except:
raise Http404
plz view my code .. i m littlebit confuse in absolute url.. it returns title of the product after clicking some link but it doesnt give me the title if i change produc to other. for eg:http:/127.0.0.1:8000/product/T-shirt/ gives title but wheni hit http:/127.0.0.1:8000/productS/T-shirtgives eroror
It's hard to tell what your actual problem is from the way you've expressed your question, but there are several issues:
Models, unless a single entity represents a plurality of something, must be named in singular. Also, following Python practices, they should be capitalized.
class products(...) should be class Product(...).
Since title is not an unique field, as soon as you have multiple products named "T-shirt", your single view will crash, since .get() refuses to work if more than one object matches the query.
Rethink your URL scheme (to e.g. use that unique slug field you have).
The product/.../ URL should be in products/urls.py, not your project URLs.
Move it there.
Unless you're absolutely sure what you're doing, don't use a bare except:, since it will happily hide any exception. You're looking for except ObjectDoesNotExist:, probably.
You should consider using generic class-based views.
I am finding it quite difficult to display django models in template. The Model does not show at all in the template. Any help will indeed be appreciated.
models.py
from django.db import models
from django.urls import reverse
from datetime import datetime
class Blog(models.Model):
name= models.CharField(max_length = 200)
company= models.CharField(max_length = 200)
post = models.CharField(max_length = 200)
author= models.ForeignKey('auth.User', on_delete = models.PROTECT)
mantra= models.CharField(max_length = 200, help_text='make it short and precise')
photo= models.ImageField(upload_to='photos/jobs/%Y/%m/%d/', blank=False, null=False)
publish = models.BooleanField(default =True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index')
views.py
from django.shortcuts import render
from django.views.generic import TemplateView,ListView
from django.views.generic.edit import CreateView
from .models import Blog
class Home(ListView):
model = Blog
context_object_name = 'test'
template_name='test.html'
fields = ['name', 'company', 'post', 'author', 'mantra', 'continent', 'photo']
urls.py
from django.urls import path
from .views import Home
urlpatterns=[
path('', Home.as_view(), name='index'),
]
Template
<p>{{test.name}}</p>
<p>{{test.author}}</p>
<p>{{test.post}}</p>
You should loop on the queryset:
{% for object in test %}
<p>{{object.name}}</p>
<p>{{object.author}}</p>
<p>{{object.post}}</p>
{% endfor %}
i want get my album.object.all() coding running in my web site. i have included data but after putting it in urls.py file it doesnt find the path to response. please help me.
this is django 1.11.2
my urls.py file
from django.conf.urls import url
from django.contrib import admin
from myapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^album/?$', views.music, name='music'),
url(r'^album/(?P<album_id>\d+)/$', views.detail, name='detail'),
url(r'^Database/?$', views.Database, name='Database'),
]
my views.py file
from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Album
# Create your views here.
def home(request):
return render(request, 'index.html')
def music(request):
all_albums = Album.objects.all()
context ={'all_albums': all_albums,}
return render(request, 'album.html', context)
def detail(request, album_id):
return HttpResponse("<h2>Details for album id: " + str(album_id) + "</h2>")
def Database(request):
return render(request, 'data.html')
my model.py page
from django.db import models
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000)
def __str__(self):
return self.album_title+ ' - ' +self.artist
class Song(models.Model):
Album = models.ForeignKey(Album, on_delete=models.CASCADE)
#any songs of the related to the deleted album will be deleted
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=200)
want to use it get the whole directory by <pk>=album_id
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(...)