I have followed many examples and docs, but cannot get this right.
I'm trying to make my Elasticsearch index whenever I update a model. Using the 'autoindex' does not log M2M's.
When I change a value inside Tag it should update the index of all the Items is is in
I am using django-elasticsearch (here) which is a wrapper around elasticsearch-py.
When I try connect(tag_index, sender=Tag.item.through) it cannot find tag as it hasn't been imported by models yet.
How is this correctly achieved?
class Tag(models.Model):
name = models.CharField(max_length=500, blank=True)
taglevel = models.IntegerField(null=True, blank=True)
def tag_index(instance, **kwargs):
Task.instance.es.do_index()
class Item(EsIndexable, models.Model):
title = models.CharField(max_length=100, blank=True)
tag = models.ManyToManyField('Tag', blank=True)
class Elasticsearch(EsIndexable.Elasticsearch):
serializer_class = TaskEsSerializer
fields = ['title', 'tag']
#receiver(post_save, sender= Task)
def index_elastic(instance, **kwargs):
instance.es.do_index()
m2m_changed.connect(tag_index, sender=Item.tag.through)
Ok, it isn't as "smart" as I thought it was. You need to refer to functions in each model
class Tag(models.Model):
name = models.CharField(max_length=500, blank=True)
taglevel = models.IntegerField(null=True, blank=True)
#receiver(post_save, sender= Tag)
#receiver(post_delete, sender= Tag)
def index_tag(instance, **kwargs):
Item.objects.get().es.do_index()
def tag_index(instance, **kwargs):
instance.es.do_index()
class Item(EsIndexable, models.Model):
title = models.CharField(max_length=100, blank=True)
tag = models.ManyToManyField('Tag', blank=True)
class Elasticsearch(EsIndexable.Elasticsearch):
serializer_class = ItemEsSerializer
fields = ['title', 'tag']
#receiver(post_save, sender= Item)
def index_elastic(instance, **kwargs):
instance.es.do_index()
Related
i am trying to create a blog by the admin panell. but i am not able to save. Can you please help.
Model.py
class blog(models.Model):
author = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
city_id = models.AutoField(primary_key=True)
blog_title=models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
slug = models.CharField(max_length=500, blank=True)
tags = TaggableManager()
blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True)
blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True)
written_by = models.CharField(max_length=200, default='sandeep')
image_banner= models.ImageField(upload_to='image_banner')
medium_thumbnail = models.ImageField(upload_to='medium_thumbnail')
content = RichTextField() # RichTextField is used for paragraphs
is_authentic=models.BooleanField(default=False)
class Meta: # Plurizing the class name explicitly
verbose_name_plural = 'blog'
def __str__(self): # Dundar Method
return self.blog_title
def save(self, *args, **kwargs): # Saving Modefied Changes
if not self.slug:
self.slug = slugify(self.blog_title)
view.py
def tags(request,tags):
blogs = blog.objects.filter(
Q(blog_title__icontains = tags.replace('-',' ')) |
Q(content__icontains = tags.replace('-',' '))
)
print(tags)
return render(request, 'services/blog-with-sidebar.html',
{'blogs': blogs,'media_url':settings.MEDIA_URL})
For some reason when I'm trying to save the tags and the data I'm getting this error:
I am trying to implement Q search on my APIView, but it says invalid lookups name which is strange. I have added the search fields according to the fields of the models.
My view:
from django.db.models import Q
class PrdouctSearchAPIView(ListAPIView):
permission_classes = [AllowAny]
# def list(self, request, *args, **kwargs):
def get(self, request, *args, **kwargs):
qur = self.request.query_params.get('search')
item = Product.objects.filter(Q(category__name__icontains=qur)|
Q(brand__name__icontains=qur)|
Q(description__icontains=qur)|
Q(collection__name__icontains=qur)|
Q(variants__name__icontains=qur))
serializer = ProductSerializer(item,many=True)
return Response(serializer.data)
My models:
class Product(models.Model):
merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True)
category = models.ManyToManyField(Category, blank=False)
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
featured = models.BooleanField(default=False) # is product featured?
description = RichTextField(blank=True)
variants = models.ManyToManyField(Variants,related_name='products')
class Category(models.Model):
#parent = models.ForeignKey('self',related_name='children',on_delete=models.CASCADE,blank=True,null=True)
name = models.CharField(max_length=100, unique=True)
image = models.ImageField(null=True, blank=True)
class Brand(models.Model):
brand_category = models.ManyToManyField(Category,blank=True,null=True)
name = models.CharField(max_length=100, unique=True)
class Collection(models.Model):
name = models.CharField(max_length=100, unique=True)
image = models.ImageField(null=True, blank=True)
My url is :
path('api/productsearch',views.PrdouctSearchAPIView.as_view(),name='api-productsearch'),
As we can see there are fields "category__name" and such not only "name", but the error says invalid lookup "name".
I'm trying to set reportNr field default to a number that iterates every time a report has been added. Is there any way to do this?
In models.py:
from django.db import models
class RapportQuerySet(models.query.QuerySet):
def active(self):
return self.filter()
class RapportManager(models.Manager):
def get_queryset(self):
return RapportQuerySet(self.model, using=self._db)
def all(self):
return self.get_queryset().active()
class Rapport(models.Model):
objects = RapportManager()
reportNr = models.TextField(blank=True, default="?")
avd = models.TextField(max_length=10, null=True, blank=True)
ritningNr = models.TextField(max_length=20, null=True, blank=True)
enhetsNr = models.TextField(max_length=40, null=True, blank=True)
atgard = models.TextField(max_length=100,null=True, blank=True)
namn = models.TextField(max_length=100,null=True, blank=True)
anstNr = models.TextField(max_length=100,null=True, blank=True)
date = models.DateTimeField()
file = models.FileField(null=True, blank=True)
def __str__(self):
return self.reportNr
what is the report (I do not see any relations with report), if it model instance then:
reportNr = = models.IntegerField(default=0) - must be integer
Also you can override create method
def save(self, *args, **kwargs):
super(Report, self).save(*args, **kwargs)
#Iterate the reportNr
Hopefully, I understand right) If not can you describe problem in details
Django 'CategorisedListView' object has no attribute 'slug' or Page not found (error 404) issue
I'm on Django 2.0, using generic class list view. I have tried dynamic url based on slug and queryset filter on slug to get list of charts by category.
Please help! I've been stuck here for a couple of days since.
views.py
class CategoriesView(generic.ListView):
template_name = 'Bokeh/categories.html'
context_object_name = 'all_categories'
def get_queryset(self):
return Category.objects.all()
class CategorisedListView(generic.ListView):
model = Category
template_name = 'categories/list_of_charts_by_category.html'
context_object_name = 'categorised'
def get_queryset(self):
self.category = get_object_or_404(Category, name = self.kwargs['slug'])
return Chart.objects.filter(category=self.slug)
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
image_file = models.ImageField(default=None, unique=True)
slug = models.SlugField(max_length=100, unique=True)
parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True, null=True, related_name='children')
def __str__(self):
return self.name
def get_absolute_url(self):
return '{slug}/'.format(slug=self.slug)
class Meta:
ordering = ('name',)
verbose_name = 'Category'
verbose_name_plural = 'Categories'
class Chart(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(max_length=250)
url = models.URLField(default=None, blank=True)
embed_url = models.TextField(default=None, blank=True)
image_file = models.ImageField(default=None, unique=True)
code_file = models.FileField(default=None, blank=True, unique=True)
chart_library = models.CharField(max_length=250)
author = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
tag = TaggableManager()
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.name + ' - ' + self.chart_library
def get_absolute_url(self):
return reverse('Bokeh:detail', kwargs={'pk': self.pk})
def read_file(self):
data = self.code_file.path
with open(self.code_file.path, 'r', encoding='UTF-8') as data:
content = data.read()
return content
class Meta:
ordering = ('name',)
urls.py
path("categories/", views.CategoriesView.as_view(), name='categories'),
# /Bokeh/categories/<category_slug>
path("categories/<slug:slug>/", views.CategorisedListView.as_view(), name='list_of_charts_by_category'),
it is supposed to query the database when a specific category is clicked and return the list of charts categorised under that specific category. However, the page throws 'CategorisedListView' object has no attribute 'slug'
The lookup you're doing in get_queryset() isn't quite right. Firstly, you seem to be looking up the Category by name rather than by the slug. Then you try and filter the Charts using their category attribute, but instead of passing the category you pass a non-existent attribute self.slug.
Try changing the implementation to this:
def get_queryset(self):
# Lookup the Category using it's slug attribute, not name, and assign to local variable
category = get_object_or_404(Category, slug=self.kwargs['slug'])
# Now lookup the Charts using the category we just looked up
return Chart.objects.filter(category=category)
I am working on a blog like project but different and I have recently started learning Django. So, in my app we have categories and tags as well. Now there's an Entry model which has ManyToMany relation with both Category and Tag. Now I am trying to get all the Entries which falls under a particular category, it's a similar feature that we have in blogs.
Following is my Tag and Category Model.
class CategoryQuerySet(models.QuerySet):
def category_menu(self):
return self.filter(intopmenu=True)
def top_catgories(self):
return self.order_by("views")[:5]
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
views = models.IntegerField(default=0)
intopmenu = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
slug = models.SlugField(unique=True)
objects = CategoryQuerySet.as_manager()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Meta:
verbose_name = "Entry Category"
verbose_name_plural = "Entry Categories"
ordering = ["created"]
class Tag(models.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=200, unique=True)
def __str__(self):
return self.slug
Following is my Entry Model.
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
def most_liked(self, num):
return self.order_by("-likes")[:num]
def most_views(self, num):
return self.order_by('-views')[:num]
class Entry(models.Model):
image = models.ImageField(upload_to='entries_images/', null=True)
image_alt = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=50, blank=True)
text = models.CharField(max_length=500, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
source = models.URLField(blank=True)
slug = models.SlugField(unique=True)
categories = models.ManyToManyField(Category)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Entry, self).save(*args, **kwargs)
def __str__(self):
return self.text
class Meta:
verbose_name = "Entry"
verbose_name_plural = "Entries"
ordering = ["created"]
In my urls.py I have the following url to view all entries by that fall under a particular category.
url(r'^category/(?P<category_slug>[\w\-]+)/$', views.category, name='category'),
Apparently, I don't understand how to write the view to retrieve list of all the entries falling under particular category or tag. Any help will be appreciated. I did refer many blog posts on the web regarding my problem and also searched SO, 1 is a similar question I found but that didn't help much.
try:
def category(request,category_slug):
category = get_object_or_404(Category,slug=category_slug)
return render(request,'template_name.html',{'category':category,'posts':category.entry_set.all()})
More information on https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/