No reverse match django class based views - python

I m new to Django and I am learning it through a project but m stuck with this error which says that NoReverseMatch at /product/create/
here is my models.py file
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
# Create your models here.
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null= True,blank=True)
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
This is my views.py but I m not sure if there is something wrong with my views
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable']
class ProductUpdate(UpdateView):
model = Product
fields = ['name', 'image', 'description', 'price', 'stock','available', 'negiotiable']
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')

I can't tell if this is the problem without the traceback or urls.py but I'm guessing you need to auto-generate the slug field by overriding the save method in the Product model. Instructions here: http://fazle.me/auto-generating-unique-slug-in-django/
Or you could try this:
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null= True,blank=True)
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail', args=[self.slug])
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Product, self).save(*args, **kwargs)
Note that this way you will have to change db_index to unique for the name field.

Related

Python/Django MakeMigrations Error Traceback

Here is what appears when i try to use python manage.py makemigrations
traceback error
Here is models.py code
----------------------code-------------------------------------
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=255, unique=True)
class Meta:
verbose_name_plural = 'categories'
# def get_absolute_url(self):
# return reverse("store:category_list", args=[self.slug])
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator')
title = models.CharField(max_length=255)
author = models.CharField(max_length=255,default='admin')
description = models.TextField(blank=True)
image = models.ImageField(upload_to='images/')
slug = models.SlugField(max_length=255)
price = models.DecimalField(max_digits=4, decimal_places=2)
in_stock = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Products'
ordering = ('-created',)
def __str__(self):
return self.title
------------------code end-------------------------------
im new and i dont know whats the problem

How can I filter the field so that when I select a category, only those products that belong to this category are displayed?

My models, category and product. Each product has a category field, which is linked through ForeignKey.
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.TextField()
image = models.ImageField(upload_to='category', blank=True)
class Meta:
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category')
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='product', blank=True)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return self.name
And views, a product category can be selected and when I click on a category, I want the product to appear only in that category
class CategoriesList(LoginRequiredMixin, ListView):
login_url = 'login/'
template_name = 'index.html'
model = Category
class ProductsList(ListView):
template_name = 'products.html'
model = Product
def get_queryset(self):
return super().get_queryset().filter(category=category_id)

Related Field got invalid lookup: name

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".

How to auto generate slug from my Album model in django 2.0.4

I have an Album field with a list of Songs
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000,blank=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.album_title
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
artist = models.CharField(max_length=250, blank=True)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=100)
def __str__(self):
return self.artist
I would like to know how to generate slugs from the album title. I am following a tutorial which is using django 1.8 which uses regular expressions to implement this task. But from looking through the documentation they have introduced a more simpler approach ('').
So can you help explain how I can implement it for a beginner to understand not only in this context but if possible across board.
Thanks in advance.
Django autogenerates the slug from the string object you pass to the slug field.
# Import slugify to generate slugs from strings
from django.utils.text import slugify
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000,blank=True)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.album_title)
super(Album, self).save(*args, **kwargs)
def __str__(self):
return self.album_title
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE)
artist = models.CharField(max_length=250, blank=True)
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.song_title)
super(Song, self).save(*args, **kwargs)
def __str__(self):
return self.artist
To use signals,
Here is the tutorial where I found the solution for this
models.py
import these stuff
from django.utils.text import slugify
from django.dispatch import receiver
from django.db.models.signals import pre_save
Add this under your model.
class Album(models.Model):
artist = models.CharField(max_length=250)
album_title = models.CharField(max_length=250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=1000,blank=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.album_title
#receiver(pre_save, sender=Store)
def store_pre_save(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = slugify(instance.song_title)
Make sure it's under the class and the def,
otherwise you will get an error
**models.py**
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
**admin.py**
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display=('title', 'slug', 'author', 'publish',status')
list_filter=('status', 'created', 'publish', 'author')
search_fields=('title', 'body')
prepopulated_fields={'slug': ('title',)}
raw_id_fields=('author',)
date_hierarchy='publish'
The above models.py and admin.py
when you write your post title instantly your slug automatically populated you dont write slug

I am getting MultiValueDictKeyError while editing the existing data and saving it in django admin?

I can be able to add the first data entry but after that editing the existing data or adding the new data causes MultiValueDictKeyError at /admin/api/digitalpost/9b763eae-cb8b-4473-af5d-5d4d91323ae1/change/
"u'contentlist_set-0-basemodel_ptr'".
Models.py
class BaseModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
version = models.FloatField(default=1.0)
created_at = models.DateTimeField(auto_now_add=True)
def image_tag(self):
self.url = 'http://127.0.0.1:8000/' + self.picture.name
return u'<img src="%s" />' % self.picture.url
image_tag.short_description = 'Thumbnail'
image_tag.allow_tags = True
class Client(BaseModel):
parent = models.ForeignKey('self',on_delete=models.SET_NULL, blank=True, null=True, related_name='brands')
name = models.CharField(max_length=120, unique=True)
picture = models.ImageField(upload_to="static/images/digital")
list_display = ('name','parent',)
description = models.CharField(max_length=250)
def __unicode__(self):
if self.parent:
return "{} {}".format(self.parent.name, self.name)
else:
return self.name
def parent_brand(self):
return str(self)
parent_brand.short_description = 'NAME'
class Meta:
ordering = ['parent__name','name']
class Category(BaseModel):
title = models.CharField(max_length=64, unique=64)
description = models.CharField(max_length=256, null=True, blank=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['-created_at']
verbose_name_plural = "categories"
class DigitalPost(BaseModel):
title = models.CharField(max_length=100)
brand = models.ForeignKey(Client, on_delete=models.SET_NULL, blank=True, null=True, )
launch_date = models.DateField(blank=True, null=True)
order = models.IntegerField()
def __unicode__(self):
return self.title
class Meta:
ordering = ['order']
class ContentList(BaseModel):
title = models.CharField(max_length=100)
description = models.CharField(max_length=256, null=True, blank=True)
picture = models.ImageField(upload_to="static/images/digital", blank=True)
post = models.ForeignKey(DigitalPost, on_delete=models.SET_NULL, null=True, blank=True)
# post_category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
admin.py
class ContentListForm(forms.ModelForm):
class Meta:
model = models.ContentList
fields = '__all__'
class ContentListInline(admin.TabularInline):
model = models.ContentList
form = ContentListForm
fk_name = 'post'
exclude = ('id', 'version')
class DigitalPostForm(forms.ModelForm):
class Meta:
model = models.DigitalPost
fields = '__all__'
#admin.register(models.DigitalPost)
class DigitalPostAdmin(ActiveStaffPermittedModel):
inlines = [
ContentListInline,
]
form = DigitalPostForm
actions = ['delete_selected']
exclude = ('id', 'version',)
readonly_fields = ('created_at',)
def delete_selected(self, request, obj):
for o in obj.all():
self.delete_one(request, o)
delete_selected.short_description = "Delete selected Posts"

Categories