I'm stuck in the following problem: When I try to implement Autocomplete following the example in this link, modifying search_index.py as follows:
import datetime
from haystack import indexes
from myapp.models import Note
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='user')
pub_date = indexes.DateTimeField(model_attr='pub_date')
# We add this for autocomplete.
content_auto = indexes.EdgeNgramField(model_attr='content')
def get_model(self):
return Note
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return Note.objects.filter(pub_date__lte=datetime.datetime.now())
I get the following error:
Failed to add documents to Solr: [Reason: Error 400 ERROR: [doc=example.autor.1] unknown field 'content_auto'].
Of course, "content_auto" is not and attribute of the class autor, but accordingly to the Autocomplete documentation, that's needed.
Related
I am new to Django. I am working on a project that uses weather API to get the weather.Everything was working fine until models.py was made and imported city on views.py
I use ver. 1.11.13
models.py
from __future__ import unicode_literals
from django.db import models
class city(models.Model):
name = models.CharField(max_length=25)
def __str__(self):
return self.name
class Meta:
verbose_name_plural ='cities'
views.py ( Error comes at cities = city.objects.all())
import requests
from django.shortcuts import render
from .models import city
def index(request):
url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd'
city = 'Lucknow'
cities = city.objects.all()
weather_data =[]
for city in cities:
r= requests.get(url.format(city)).json()
city_weather = {
'city':city.name ,
'temperature' :r['main']['temp'],
'description' :r['weather'][0]['description'],
'icon' :r['weather'][0]['icon'] ,
}
weather_data.append(city_weather)
print(weather_data)
context = {'weather_data' : city_weather}
return render(request,'weather/weather.html', context)
Solve this issue.
For dynamic table name you can use like
table_name = 'MyTable'
model = getattr(YOURAPP.models, table_name)
model.objects.all()
In your index function, you write:
def index(request):
url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd'
city = 'Lucknow'
cities = city.objects.all()
# ...
As a result, you defined city here as a locally scoped variable, and with a string value. A quick fix is to rename the string, like:
def index(request):
url= 'http://api.openweathermap.org/data/2.5/weather?q={}& units=imperial&appid=e1a2ef38103d2e572d316e38452e2acd'
city_ = 'Lucknow'
cities = city.objects.all()
# ...
# use city_ for the string element
But nevertheless, a class typically starts with an uppercase, so I would advice to rename your class City instead of city.
Furthermore I find it weird that you defined this string, since nowehere in the view, you are supposed to use it. The url.format(..) should probably use the city.name of the City object in the queryset.
Django:1.11.5
Python:3.5.2
Markdown 2.6.9 https://pypi.python.org/pypi/Markdown/
views.py
from django.shortcuts import render
from .models import Post
import markdown
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
Post.content = markdown.markdown(Post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
# Create your views here.
models.py
from django.db import models
import django.utils.timezone as timezone
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(blank = True, null = True)
pub_date = models.DateTimeField(default=timezone.now)
update_time = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category)
# Create your models here.
Error message
AttributeError at /
'DeferredAttribute' object has no attribute 'strip'
Request Method: GET
Request URL: http://www.balinzuoqi.com/
Django Version: 1.11.5
Exception Type: AttributeError
Exception Value:
'DeferredAttribute' object has no attribute 'strip'
Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/__init__.py in convert, line 355
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/data/mysite',
'/usr/local/bin',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-i386-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Do not know where there is a problem.
Remove Post.content = markdown.markdown (Post.content), show normal!
English is not my native language; please excuse typing errors.
You are reading content from and writing content to the Post class, not an instance of the class. You need to iterate through the list and update each instance:
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
for post in Post_list:
post.content = markdown.markdown(post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
Whether that is a recommended way of converting Markdown to HTML to pass to a template is another matter. Its been a few years since I've used Django, but that wasn't how it used to be done. However, that is a different question.
Regardless, you were not actually passing any Markdown text to the Markdown parser as you were not using an instance of the class. With the for loop I added above, the Markdown content for each 'Post' is now being passed to the Markdown parser.
I'm new to haystack/solr so this is likely a newbie error. I am using solr with haystack.
When I run update_index, it seems to be duplicating the records. I am getting:
get() returned more than one Doctor -- it returned 3!
for this piece of code:
self._object = self.searchindex.read_queryset().get(pk=self.pk)
if I run update_index again, the number return increases by one and if I run rebuild_index, it will work showing only one record until I update again.
So from that, It seems that update_index is duplicating records in the index. How do I get it from not doing that?
Here is my haystack search index:
from haystack import indexes
from .models import Doctor, Zipcode
from django.contrib.gis.measure import D
from django.conf import settings
class DoctorIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
name = indexes.EdgeNgramField(model_attr='name')
specialty = indexes.MultiValueField()
condition = indexes.MultiValueField()
procedure = indexes.MultiValueField()
premium = indexes.BooleanField()
location = indexes.LocationField(model_attr='main_office__location')
latitude = indexes.DecimalField(indexed=False)
longitude = indexes.DecimalField(indexed=False)
docid = indexes.IntegerField()
slugify_name = indexes.CharField(indexed=False)
rendered = indexes.CharField(use_template=True, indexed=False)
premium_rendered = indexes.CharField(use_template=True, indexed=False)
include = indexes.BooleanField(indexed=False)
def get_model(self):
return Doctor
def prepare_specialty(self, obj):
return ["%s %s"%((specialty.parent.name if specialty.parent else ""), specialty.name) for specialty in obj.specialty.all()]
def prepare_condition(self, obj):
return [condition.name for condition in obj.conditions.all()]
def prepare_procedure(self, obj):
return [procedure.name for procedure in obj.procedures.all()]
def prepare_premium(self, obj):
return obj.display()['premium']
def prepare_latitude(self, obj):
return obj.main_office.lat
def prepare_longitude(self, obj):
return obj.main_office.lon
def prepare_docid(self,obj):
return obj.id
def prepare_slugify_name(self,obj):
return obj.slugify_name()
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(specialty__search_include=True)
Here is my solr schema: https://gist.github.com/anonymous/5d5b011ca7fa0f3f3e29
I've done a lot of googling, but can't seem to find an answer to this.
So this one was tricky to track down, but the problem was actually in my index_queryset function.
This:
return self.get_model().objects.filter(specialty__search_include=True)
should actually be this:
return self.get_model().objects.filter(specialty__search_include=True).distinct()
That function had duplicates in it and was causing my error, not the solr schema like I had thought. Specialty is a ManyToManyField.
I just faced the same issue.
According to this topic it is necessary to remove .pyc files. Inside of a project simply do the next (for Linux):
find . -name "*.pyc" -type f -delete
I have been having some issues with django-haystack and need some help.
I run a site that indexes projects and certain projects are in a status where they should not be seen, ie status='DE', status='PR'
my current setup is.
from haystack.indexes import *
from haystack import site
from models import Project
class ProjectIndex(RealTimeSearchIndex):
project_name = CharField(document=True, use_template=True)
description = CharField(use_template=True, model_attr='description')
location = CharField(use_template=True, model_attr='location')
owner = CharField(model_attr='owner')
def search(self):
return Project.objects.filter(status='AP').exclude(status='PR').exclude(status='DE')
def index_queryset(self):
"""Used when the entire index for model is updated."""
return Project.objects.filter(status='AP').exclude(status='PR').exclude(status='DE')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Project.objects.filter(status='AP').exclude(status='PR').exclude(status='DE')
def read_queryset(self):
"""Used when the entire index for model is updated."""
return Project.objects.filter(status='AP').exclude(status='PR').exclude(status='DE')
site.register(Project, ProjectIndex)
I managed to solve this issue by updating from 1.1 to 1.2
then all of the sudden I started receiving these Caught VariableDoesNotExist while rendering: Failed lookup for key [object] in u'None'
Googled it and found out that certain items might have disappeared out of the system and there is a handy command for that.
now I have a cronjob that does the following /usr/bin/python2.6 /www/mysite/manage.py update_index --remove every few hours
I've created a Feed subclass to export a simple feed of news
#urls.py
from django.conf.urls.defaults import *
from litenewz.feeds import NewsFeed
feeds = {
'news': NewsFeed,
}
urlpatterns = patterns(
'',
(r'^feeds/(?P<url>.*)/$',
'django.contrib.syndication.views.feed',
{'feed_dict': feeds}),
)
#feeds.py
from django.contrib.syndication.feeds import Feed
from litenewz.models import News
class NewsFeed(Feed):
title = 'example news'
link = 'http://example.net'
description = 'Latest Newz from example.'
item_author_name = '...'
item_author_email = '...'
item_author_link = 'http://example.net'
def items(self):
return News.objects.order_by('-time')[:15]
#models.py
from django.db import models
from django.utils.translation import ugettext as _
from datetime import datetime
class News(models.Model):
class Meta:
ordering = ('-time', )
verbose_name = _('News')
verbose_name_plural = _('News')
title = models.CharField(
_('Title'),
max_length=512)
time = models.DateTimeField(
_('Date and time'),
default=datetime.now
)
content = models.TextField(
_('Content'))
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self):
return ('home', (), {})
As you can see the Feed subclass' items() method returns the first 15 objects in News.objects.order_by('-time'):
def items(self):
return News.objects.order_by('-time')[:15]
Nevertheless, only one item is exported in the feed: hxxp://www.sshguard.net/litenewz/feeds/news/
Unfortunately, there are two objects of the News model:
>>> from litenewz.models import *
>>> News.objects.all()
[<News: Version 1.5 and timing>, <News: SSHGuard news>]
Any help?
I prefer not to switch to Django 1.2, unless this is strictly necessary to solve the issue described.
Update: the RSS returned indeed contains both the objects, but the RSS is not valid and thus readers such as Safari's are fooled:
http://validator.w3.org/feed/check.cgi?url=http://www.sshguard.net/litenewz/feeds/news/
Looks like it's not valid because you've not generated your guid correctly:
The validator says:
This feed does not validate.
line 25, column 83: guid values must not be duplicated within a feed:
... )</author><guid>http://www.sshguard.net/</guid></item></channel></rss>
The reason is that your get_absolute_url method on your News model returns the same thing for each News instance - do you have unique URLs for each News item? If so you should use that rather than:
def get_absolute_url(self):
return ('home', (), {})
The validation error appears to be from the <guid> element in each item of your feed. As far as I can tell, this is auto-generated from the get_absolute_url() method of the model, in your case the News model. Have you defined that method? If so, is it actually returning a distinct URL for each item?