I's using django 1.6 and have a model for a blog but when saving the content I get category id can not be blank but I don't understand this error. I have tried looking at the code trying different things but it doesn't seem to be working.
class Category(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
description = models.TextField(null=True, blank=True)
class Meta:
verbose_name_plural = "Categories"
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self):
return ('view_category', None, {'slug': self.slug})
class Blog(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=2000)
extended = models.TextField(null=True, blank=True)
category = models.ForeignKey(Category)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
verbose_name = 'Blog post'
verbose_name_plural = 'Blog posts'
ordering = ('-updated',)
def __unicode__(self):
return '%s' % self.title
#permalink
def get_absolute_url(self, ):
return('view_questions', None, {'slug': self.slug,})
def save(self):
super(Blog, self).save()
if not self.slug:
self.slug = '%d/%s' % (
self.pk, slugify(self.title)
)
super(Blog, self).save()
when saving the content I get category id can not be blank but I don't
understand this error.
category = models.ForeignKey(Category)
That line means that a blog post must belong to a category. In your blog table, the category foreign key is called category_id.
You can either make sure to add a category; blog.category = Category.objects.get(...) for example OR you can make the category optional:
category = models.ForeignKey(Category, blank=True, null=True)
Related
Old MODELS.py
when use tags by many_to_many fields
class Tag(models.Model):
tag_name = models.CharField(max_length=64, unique=True)
tag_slug = models.SlugField(max_length=64, unique=True)
created_on = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.tag_name
def get_absolute_url(self):
return reverse("news:tag-detail", kwargs={"slug": str(self.tag_slug)})
class News(models.Model):
title = models.CharField(max_length=192, unique=True)
slug = models.SlugField(max_length=192, unique=True)
cover_photo = models.ImageField(upload_to='news', blank=True, null=True)
summary = models.CharField(max_length=280)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author')
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=1)
# tags = models.ManyToManyField(Tag, blank=True, related_name='post_tag')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("news:post", kwargs={"slug": str(self.slug)})
current models.py
After install Django_Taggit
i remove tags model and rewrite tags line
class News(models.Model):
title = models.CharField(max_length=192, unique=True)
slug = models.SlugField(max_length=192, unique=True)
cover_photo = models.ImageField(upload_to='news', blank=True, null=True)
summary = models.CharField(max_length=280)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author')
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=1)
tags = TaggableManager()
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("news:post", kwargs={"slug": str(self.slug)})
Also i remove tags from view.py and urls path and update html
but when i try to 'python manage.py migrate' i face this error
ValueError: Cannot alter field news.News.tags into news.News.tags - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through
= on M2M fields)
First remove the tags field and (makemigrations->migrate), then as you don't have tags as a field anymore add the new taggit field and again (makemigrations->migrate).
If you want to save the current tags, I can think of couple of options.
Create new field for example tags_taggit, and then run a script to translate the current tags into the new tags_taggit field. Then proceed with the steps I told you first
Create fixtures, then run a script to iterate over the fixtures and save the tags into the new field.
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 still learning to use Django and so I am a bit unclear on something.
I have a product model and category model. A product can lie in multiple categories and multiple categories can have the same product.
So, its a many to many relationship. Now, I want to allow the user to select multiple categories from the html and then I want to save the categories and link them to the category object in my product model. I am completely lost about it.
One way would be to use Modelform but I dont want to go that way. Is there any other way I can accomplish this?
models.py:
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
help_text='Unique value for product page URL, created from name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255,
help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:categories', kwargs={'category_slug': self.slug})
class Meta:
ordering = ['-created_at']
verbose_name_plural = 'Categories'
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True,
help_text='Unique value for product page URL, created from name.')
brand = models.CharField(max_length=50)
sku = models.CharField(max_length=50)
price = models.DecimalField(max_digits=9, decimal_places=2)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
imageurls = models.CharField(max_length=1000)
is_active = models.BooleanField(default=True)
is_bestseller = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField(Category)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('catalog:products', kwargs={'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
ordering = ['-created_at']
part of views.py:
if request.method =='POST':
print ('entered')
name = request.POST['name']
brand = request.POST['brand']
sku = request.POST['sku']
price = request.POST['price']
quantity = request.POST['quantity']
description = request.POST['description']
imageurls = request.POST['urls']
print('imageurls',imageurls)
categorylist = request.POST['categories']
print('categorylist',categorylist)
categories = re.findall(r"[\w']+", categorylist)
print categories
imageurls = imageurls.split('~')
print('iageurls',imageurls)
for x in categories:
categoryobj = Category.objects.filter(name=x).values()
print ('categoryobj',categoryobj)
# Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)
return HttpResponse('success')
Try to save the above way gives me error.
product=Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls)
category_queryset = []
for x in categories:
category = Category.objects.filter(name=x).first()
category_queryset.append(category)
product.categories.set(category_queryset)
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/
I have a model like this
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
def __str__(self):
return "%s"%self.title
class Video(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
idlink = models.CharField(max_length=50)
posted = models.DateField(db_index=True, auto_now_add=True)
category = models.ForeignKey(Category)
def __str__(self):
return "%s"%self.title
And my views.py is
def list_video_cat(request, slug):
video = Video.objects.filter(category__slug=slug).order_by('-posted')
return render(request, 'category.html', {'videos':video})
I want to show my post new to old, but it seems to did not work at this situation. What should I do?
P/S the "duplicated post" does not solve my problem