AttributeError: 'AttributeValueAdmin' object has no attribute 'urls' - python

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

Related

How build a category model after building legacy model in Django REST Framework

Hello, I have a question about improving legacy models.
The Material model is old model, and i want to make category by using new model 'type'. But i have a little problem with when i use admin site. In admin site, i hope to choose the 'type' first, and upload data .. how can i make better
models
# new model
class MaterialType(BaseModel):
type = models.CharField(choices=MaterialTypeChoice.choices, max_length=50, null=True, blank=True)
def __str__(self):
return self.type
# old model
class Material(models.Model):
type = models.ForeignKey(MaterialType, verbose_name=, null=True, blank=True, on_delete=models.SET_NULL)
name = models.CharField max_length=50, null=True, blank=True)
size = models.CharField(max_length=50, null=True, blank=True)
unit = models.CharField(max_length=5, null=True, blank=True)
price_unit = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.name
serializers
# new
class MaterialTypeListSerializer(serializers.ModelSerializer):
class Meta:
model = MaterialType
fields = ["type"]
# old
class MaterialListSerializer(serializers.ModelSerializer):
class Meta:
model = Material
fields = ["id", "type", "name", "size", "unit", "price_unit"]
views
# new
class MaterialTypeList(ListCreateAPIView):
queryset = MaterialType.objects.all()
serializer_class = MaterialTypeListSerializer
# old
class MaterialList(ListAPIView):
queryset = Material.objects.all()
filter_class = MaterialFilter
serializer_class = MaterialListSerializer
admin
#admin.register(Material)
class MaterialAdmin(ImportExportModelAdmin):
list_display = ["name", "size", "unit", "price_unit"]
list_display_links = ("name",)
list_filter = ("type",)
list_per_page = 10
# list_editable = ('type',)
search_fields = ("name", "size")
resource_class = MaterialResource
#admin.register(MaterialType)
class MaterialTypeAdmin(ImportExportModelAdmin):
list_display = ["type"]
list_filter = ("type",)
list_per_page = 10
# list_editable = ('type',)

Django Rest get link to related object in OneToOne relation

How can I get the related object link under OneToOne relation.
I have 2 models:
class Model1(models.Model):
title = models.CharField(max_length=255, null=False)
class Model2(models.Model):
mymodel1 = models.OneToOneField(Model1, on_delete=models.CASCADE)
In the Model1Serializer, how can i get the link to MyModel2 related object
ahd get a result as follows:
[
{
"title": "My obj title"
"link2mymodel2": "http://myhost/model2/pk"
}
]
where pk is the relared object
You can add it as a property to Model1.
models.py
class Model1(models.Model):
title = models.CharField(max_length=255, null=False)
#property
def link2mymodel2(self):
return self.model2.link
class Model2(models.Model):
mymodel1 = models.OneToOneField(Model1, related_name=model2, on_delete=models.CASCADE)
link = models.URLField()
serializers.py
class Model1Serializer(serializers.ModelSerializer):
link2mymodel2 = serializers.URLField()
class Meta:
model = Model1
fields = ["title", "link2model2"]

"Got KeyError when attempting to get a value for field `fk_idbrand` on serializer

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__'

How to create/update/view two modal class with one serializer

I have two model class. I want to create/update/view both model class with one serializer. I have tried but its not working.
Here is my modal class:
class PackageQuantity(models.Model):
comp_code = models.ForeignKey(
'core.SensorDevice',
on_delete=models.SET_NULL,
null=True
)
quantity = models.IntegerField()
class PackageComponent(models.Model):
pkg_code = models.CharField(max_length=255)
package = models.ForeignKey(
'PackageQuantity',
on_delete= models.CASCADE,
null=True
)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
Serializer class
class PackageQuantity(serializers.ModelSerializer):
class Meta:
model = oss.PackageQuantity
fields = ['comp_code', 'quantity',]
class PackageComponentSerializer1(serializers.ModelSerializer):
package = PackageQuantity()
class Meta:
model = oss.PackageComponent
fields = ['pkg_code','package']
Views.py
class PackageComponent1ViewSet(viewsets.ModelViewSet):
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAdminUser, permissions.IsAuthenticated,)
serializer_class = serializers.PackageComponentSerializer1
queryset = oss.PackageComponent.objects.all()
Any help will be highly appreciated. Thanks

Attribute Error after adding many=True in restframework django?

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.

Categories