We added the model named Comment as inlines in the Course model. We want to make it mandatory to fill in the fields in the Inlines model when the Save button is clicked.
# models.py
class Course(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
updated_at = models.DateTimeField(auto_now=True))
class Comment(models.Model):
CHOICES=[(1,'Approved'),
(0,'Rejected')]
course = models.ForeignKey(Course, on_delete=models.PROTECT)
opinion = models.IntegerField(choices=CHOICES)
comment = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# admin.py
class CommentInline(admin.StackedInline):
model = Comment
max_num = 1
radio_fields={'opinion':admin.HORIZONTAL}
#admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
list_display = ('title', 'category', 'reviewer', 'created_at',)
inlines = [CommentInline,]
Related
I want to use uuid field as my id (primary key) but there is something wrong with it and i can't fix it
this is my model
class Cart(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE , related_name='items')
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField()
class Meta:
unique_together = [['cart'], ['product']]
This Is MY Serializer.py
class CartItemSerializer(serializers.ModelSerializer):
class Meta:
model = Cart
fields = ['id', 'product', 'quantity']
class CartSerializer(serializers.ModelSerializer):
id = serializers.UUIDField(read_only=True)
items = CartItemSerializer(many=True)
class Meta:
model = Cart
fields = ['id', 'items']
And My Views.py is
class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet):
queryset = Cart.objects.prefetch_related('items__product').all()
serializer_class = CartSerializer
My database Is postgres Sql
My Error when I browse my api my guid
Make sure that you create a UUID field uuid = UUIDField(primary_key=True, default=None, editable=False) first before your initial migration.
If you have already done the initial migration, then drop the database and recreate it and don't forget to delete the migration files.
Run migrations again and you should be good to go.
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',)
This is the model that I want to show on the admin panel. I'm registering the model via admin.py file with admin.site.register(Ad). I tried to re-write the register line twice, and an exception appeared that the model is already registered.
class Ad(AdModel):
plate = models.CharField(max_length=50, unique=True)
description = models.TextField(max_length=500)
ad_type = models.CharField(
max_length=255,
choices=AdTypes.get_choices(),
default=AdTypes.OFFERING,
)
price = models.PositiveIntegerField(
default=0,
help_text='In cents'
)
location = models.CharField(
max_length=255,
choices=AdLocations.get_choices(),
default=AdLocations.VILNIUS,
)
user = models.ForeignKey(User, on_delete=models.PROTECT)
approved_date = models.DateField(null=True, blank=True)
approved_by = models.ForeignKey(
User, on_delete=models.PROTECT, related_name='approved_by', null=True
)
The two base models:
class UUIDBaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
class Meta:
abstract = True
class AdModel(UUIDBaseModel):
expires_at = models.DateTimeField(null=True)
is_draft = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
class Meta:
abstract = True
This is really strange, maybe that could be the problem because of the naming 'Ad'? I have a serializer for this model and everything works just fine, but the admin panel doesn't want to display it.
views.py
class AdCreateViewSet(ModelViewSet, CreateModelMixin):
serializer_class = AdCreateSerializer
permission_classes = (AllowAny,)
filter_backends = [DjangoFilterBackend]
search_fields = ('plate', 'description', 'user__email')
queryset = Ad.objects.select_related('user')
def perform_create(self, serializer):
user = User.objects.first()
serializer.save(user=user) # self.request.user)
serializers.py
class AdCreateSerializer(CustomAdSerializer):
class Meta:
model = Ad
exclude = ['expires_at']
read_only_fields = ('user',)
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
I have some issue here about the relational field (herd/herd_id) added to my model. it wont appear in the API as fields of my Animal model and AnimalSerializer djangorestframework
Here is my Animal model and serializer:
models.py
class Animal(models.Model):
this_id = models.CharField(max_length=25)
name = models.CharField(max_length=25)
species_type = models.CharField(max_length=25)
breed = models.CharField(max_length=25)
date_of_birth = models.DateField()
birth_weight = models.IntegerField()
sex = models.CharField(max_length=7)
sibling_order = models.IntegerField()
sire_id = models.CharField(max_length=20)
sire_name = models.CharField(max_length=25)
dam_id = models.CharField(max_length=25)
dam_name = models.CharField(max_length=25)
rf_id = models.CharField(max_length=25)
comment = models.TextField(max_length=250, null=True)
herd = models.ForeignKey(Herd, related_name='animals', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
class Meta:
ordering = ('name',)
serializers.py
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = (
'this_id',
'name',
'species_type',
'breed',
'date_of_birth',
'birth_weight',
'sibling_order',
'sex',
'sire_id',
'sire_name',
'dam_id',
'dam_name',
'rf_id',
'comment',
'herd_id', // <--- this field wont appear in the djangorestframework UI.
'created_at',
'updated_at',
)
read_only_fields = ('id', 'created_at', 'updated_at')
Here is the image. and look for the herd_id field it wont appear. Please help
I just change the herd_id to herd column name so django will recognize the matching serialization name.