I created a model for Slide on django. below is model.py
class Slide(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True)
text = models.CharField(max_length=300)
is_deleted = models.BooleanField(default=False)
topic_id = models.ForeignKey(Article, on_delete=models.DO_NOTHING)
created_at = models.DateTimeField("created at", auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.text
serializer.py
class SlideSerializer(serializers.ModelSerializer):
topicdetail_set = ArticleDetailSerial(many=True)
user_detail = FindOwnerSerializer(source='user', read_only=True)
author = AuthorSerializer(many=True)
class Meta:
model = Slide
fields = ('id','text', 'created_at', 'topicdetail_set', 'user_detail','author')
When I run the url for slide http://127.0.0.1:8000/article/slide/
then I got below error
AttributeError: Got AttributeError when attempting to get a value for field `topicdetail_set` on serializer `SlideSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Slide` instance.
Original exception text was: 'Slide' object has no attribute 'topicdetail_set'.
Now I am confused, Is the code that I have created is wrong? And if it is wrong then how should I fix it?
Related
When I try to change an object in django admin, I get a Type error. This happens with all the objects of that model, but not with other models. I suspect there is something wrong in my model, or at least something that django admin doesn't appreciate.
Here is the error:
TypeError at /admin/events/evenement/10/change/
type object argument after ** must be a mapping, not QuerySet
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/events/evenement/10/change/
Django Version: 4.1.5
Exception Type: TypeError
Exception Value:
type object argument after ** must be a mapping, not QuerySet
This is my model
class Evenement(models.Model):
name = models.CharField(max_length=50)
url_name = models.SlugField(max_length=50, blank=True)
datum = models.DateField()
locatie = models.CharField(max_length=100)
omschrijving = models.TextField()
evenement_type = models.ForeignKey(EvenementType, on_delete=models.PROTECT)
ideal = models.BooleanField()
aantal_honden_toegestaan = models.IntegerField(default=2)
annuleren_toegestaan = models.BooleanField(default=True)
alleen_flatcoat = models.BooleanField(default=False)
secretariaat = models.ForeignKey(Group, on_delete=models.PROTECT, limit_choices_to=limit_secretary_choices)
publicatiedatum_vanaf = models.DateField()
inschrijven_vanaf = models.DateField()
inschrijven_tot = models.DateField()
onderdelen = models.ManyToManyField(Onderdeel, blank=True)
prijs_leden = models.DecimalField(max_digits=5, decimal_places=2)
prijs_niet_leden = models.DecimalField(max_digits=5, decimal_places=2)
extra_onderdelen = models.ManyToManyField(ExtraOnderdeel, blank=True)
def __str__(self):
return '{} ({})'.format(self.name, self.datum.strftime('%d-%m-%Y'))
class Meta:
verbose_name_plural = "Evenementen"
If more info is needed I will provide of course. The model works fine when I use it in webviews and forms, so I don't understand what the problem could be. I have tested this in three different environments, all gave the same error.
I'm currently building a django app and I'm serializing my views, but when applying the serializer to the model is experiencing an error that I've been unable to fix:
models.py
class vehicles_brand(models.Model):
pk_idbrand= models.AutoField(db_column='PK_IdBrand', primary_key=True) # Field name made lowercase.
fk_idcountry= models.ForeignKey(locations_country, on_delete= models.CASCADE, db_column='FK_IdLocationCountry', related_name='Country')
name = models.CharField(max_length=20, default=None, null=True)
class Meta:
db_table = 'vehicles_brand'
verbose_name_plural = "Vehicle Brands"
def __str__(self):
return self.name
class vehicles_model(models.Model):
pk_idmodel = models.AutoField(db_column='PK_IdModel', primary_key=True) # Field name made lowercase.
name = models.CharField(max_length=20, default=None)
fk_idbrand= models.ForeignKey(vehicles_brand, on_delete= models.CASCADE, db_column='FK_IdVehicleBrand', related_name='Brand')
class Meta:
db_table = 'vehicles_model'
verbose_name_plural = "Vehicle Models"
serializers.py
class brandSerializer(serializers.ModelSerializer):
class Meta:
model = vehicles_brand
fields = '__all__'
class modelSerializer(serializers.ModelSerializer):
brand = brandSerializer(source="FK_IdVehicleBrand", many=True, read_only=True)
class Meta:
model = vehicles_model
fields = '__all__'
output:
"Got KeyError when attempting to get a value for field `fk_idbrand` on serializer `modelSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'fk_idbrand'."
I've checked my models and the serializers but for me everything seems to be ok, thanks in advance for any hint or help.
class modelSerializer(serializers.ModelSerializer):
# actually It should be Brand which is related name in table
Brand = brandSerializer(source="FK_IdVehicleBrand",many=True,read_only=True)
class Meta:
model = vehicles_model
fields = '__all__'
I have designed a table for attribute and product attributes. An attribute can have many values.
For example, an attribute called color can have values like Black, white, Grey, Maroon etc. For
this I designed a table such way
However when registering to the admin, I get AttributeError: 'AttributeValueAdmin' object has no attribute 'urls' error.
class Attribute(models.Model):
name = models.CharField(max_length=30, unique=True)
slug = models.SlugField(max_length=250, unique=True)
class Meta:
verbose_name = "Attribute"
verbose_name_plural = "Attributes"
def __str__(self):
return self.name
class ProductAttribute(SortableModel):
product = models.ForeignKey(Product,
related_name="productattribute",
null=True,
on_delete=models.CASCADE)
attribute = models.ManyToManyField(
Attribute,
through="AttributeValue"
)
class Meta:
ordering = ("sort_order",)
verbose_name = "Product Attribute"
verbose_name_plural = "Product Attributes"
class AttributeValue(SortableModel):
name = models.CharField(max_length=250)
value = models.CharField(max_length=100, blank=True, default="")
slug = models.SlugField(max_length=255)
productattribute = models.ForeignKey(ProductAttribute,
null=True,
related_name='productattribute',
on_delete=models.CASCADE)
attribute = models.ForeignKey(
Attribute, related_name="values", on_delete=models.CASCADE
)
class Meta:
ordering = ("sort_order", "id")
unique_together = ("slug", "attribute")
def __str__(self) -> str:
return self.name
admin.py
class ProductAdmin(admin.ModelAdmin):
model = models.Product
prepopulated_fields = {'slug': ('name',), }
class AttributeValueAdmin(admin.TabularInline):
model = models.AttributeValue
extra = 2
class AttributeAdmin(admin.ModelAdmin):
model = models.Attribute
prepopulated_fields = {'slug': ('name',), }
class ProductAttributeAdmin(admin.ModelAdmin):
# model = models.ProductAttribute
inlines = (AttributeValueAdmin, )
admin.site.register(models.Attribute, AttributeAdmin)
admin.site.register(models.AttributeValue, AttributeValueAdmin)
admin.site.register(models.ProductAttribute, ProductAttributeAdmin)
As per django docs on admin, the first step is to display the intermediate model by subclassing inline class for AttributeValue table like you have done
class AttributeValueInline(admin.TabularInline):
model = models.AttributeValue
extra = 2
Second step is to create admin views for both Attribute and ProductAttribute models.
class AttributeAdmin(admin.ModelAdmin):
inlines = (AttributeValueInline, )
prepopulated_fields = {'slug': ('name',), }
class ProductAttributeAdmin(admin.ModelAdmin):
inlines = (AttributeValueInline, )
Third step is to register your Attribute and ProductAttribute models
admin.site.register(models.Attribute, AttributeAdmin)
admin.site.register(models.ProductAttribute, ProductAttributeAdmin)
You don't need to register AttributeValue model as you can create/edit AttributeValue inline from either Attribute or ProductAttribute table.
For reference you can read the django docs
https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#working-with-many-to-many-intermediary-models
I'm trying to create a ViewSet for the Course model (to simply display all courses), but I'm getting the following error when trying to access it. I'm new to creating ViewSets and Django in general, what am I doing wrong?
Django 2.2
Error
AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `CourseSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'title'.
CourseViewSet
class CourseViewSet(viewsets.ModelViewSet):
def list(self, request):
queryset = Course.objects.all()
serializer = CourseSerializer(queryset)
return Response(serializer.data)
CourseSerializer
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = (
'id',
'title',
'description',
'active',
'individual_result',
'course_duration',
'video',
'manager_id'
)
models/Course
class Course(models.Model):
title = models.CharField(max_length=255, blank=False, null=False)
description = models.CharField(max_length=255, blank=True, null=True)
active = models.BooleanField(default=True)
individual_result = models.BooleanField(default=False)
course_duration = models.CharField(max_length=255, blank=True, null=True)
video = models.CharField(max_length=255, blank=True, null=True)
manager_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.title
You should serialize with many=True, since a queryset is a collection of objects that can contain zero, one, or more elements:
serializer = CourseSerializer(queryset, many=True)
For more information, see the Dealing with multiple objects section [drf-doc].
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields=('Comment','Comment_text','Comment_time','Comment_Post','Comment_User', )
class PostSerializers(serializers.ModelSerializer):
comment = CommentSerializer(many=True)
class Meta:
model = Postovo
fields = ('Postovo_id','Postovo_trending','comment', )
Models are like this
class Postovo(models.Model):
Postovo_id = models.AutoField(primary_key=True)
Postovo_type = models.ForeignKey(Type, related_name='posttype' ,default='1', editable=True)
Postovo_time = models.CharField(max_length=100,default=currentTimestamp, editable=True)
Postovo_link1 = models.CharField(max_length=1000,default='linkofimage1', editable=True)
Postovo_link2 = models.CharField(max_length=1000,default='linkofimage2', editable=True)
Postovo_person1=models.CharField(max_length=100,default='person1', editable=True)
Postovo_person2=models.CharField(max_length=100,default='person2', editable=True)
Postovo_hot=models.CharField(max_length=100,default='False', editable=True)
Postovo_trending=models.CharField(max_length=100,default='False', editable=True)
def __str__(self):
return '%s' % (self.Postovo_id)
Next
class Comment(models.Model):
Comment = models.AutoField(primary_key=True)
Comment_text = models.CharField(max_length=100)
Comment_time = models.CharField(max_length=100,default=currentTimestamp)
Comment_Post = models.ForeignKey(Postovo, related_name='commentpost' ,default='1', editable=True)
Comment_User = models.ForeignKey(RegUser, related_name='commentuser' ,default='1', editable=True)
def __str__(self):
return '%s' % (self.Comment)
In views
class Postcomment(viewsets.ModelViewSet):
queryset = Postovo.objects.all()
serializer_class = PostSerializers
ERROR
AttributeError: Got AttributeError when attempting to get a value for
field comment on serializer PostSerializers. The serializer field
might be named incorrectly and not match any attribute or key on the
Postovo instance. Original exception text was: 'Postovo' object has
no attribute 'comment'.
You need to use the related name commentpost instead of comment in PostSerializers.
class PostSerializers(serializers.ModelSerializer):
commentpost = CommentSerializer(many=True)
class Meta:
model = Postovo
fields = ('Postovo_id','Postovo_trending','commentpost', )
The error is coming because there is no comment attribute on a Postovo instance. The manager for getting all the related Comment instances is accessible using the related_name commentpost.