this is my code above.
model.py
class Produto(models.Model):
usuario = models.ForeignKey(User, null=True, blank=True)
nome = models.CharField(max_length=255)
descricao = models.TextField(null=True, blank=True, verbose_name="Descrição")
slug = models.SlugField()
class Categoria(MPTTModel):
produto = models.ManyToManyField(Produto, null=True, blank=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children',verbose_name="Categoria Pai")
nome = models.CharField(max_length=255)
descricao = models.CharField(max_length=255, null=True, blank=True)
slug = models.SlugField()
ativo = models.BooleanField(default=True)
mostra_menu = models.BooleanField(default=False)
ordem_menu = models.IntegerField(default=0)
admin.py
class CategoriaProdutoInline(admin.TabularInline):
model = Categoria.produto.through
class ProdutoAdmin(admin.ModelAdmin):
list_display = ('__unicode__','sku','descricao_curta', 'preco', 'preco_desconto', 'ativo', 'categorias', 'link')
inlines = [CategoriaProdutoInline, ImagemInLine, TagInLine]
search_fields = ('nome', 'sku', 'categoria__nome')
list_filter = ('preco', 'created_at')
prepopulated_fields = {"slug": ('nome',)}
readonly_fields = ['link']
fields = ('usuario','nome','descricao','ativo','preco','preco_desconto','slug')
Actually, the product update admin looks like this.
Insert Product Admin Page
I´ve tried to use some implementations like TreeNodeChoiceField as seem here but not works
Related
I'm getting an error when I try to serialize a many-to-many relationship
The error description that is shown to me in the console is this:
AttributeError: Got AttributeError when attempting to get a value for field produto on serializer Ped_ProSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Produto instance.
Original exception text was: 'Produto' object has no attribute 'produto'.
The models involved in the relationship are written like this:
class Produto(models.Model):
valor_unitario = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
nome = models.CharField(max_length=75)
descricao = models.TextField()
genero = models.CharField(max_length=10, default="Indefinido")
qtd_estoque = models.IntegerField()
cor = models.ForeignKey(Cor, on_delete=models.PROTECT, related_name="produtos")
tamanho = models.ForeignKey(
Tamanho, on_delete=models.PROTECT, related_name="produtos"
)
marca = models.ForeignKey(Marca, on_delete=models.PROTECT, related_name="produtos")
class Pedido(models.Model):
endereco_entrega = models.ForeignKey(
Endereco, on_delete=models.PROTECT, null=True, related_name="pedidos"
)
forma_pagamento = models.ForeignKey(
Forma_Pagamento, on_delete=models.PROTECT, null=True, related_name="pedidos"
)
usuario_dono = models.ForeignKey(
get_user_model(), on_delete=models.PROTECT, related_name="pedidos"
)
data_entrega = models.DateField()
data_pedido = models.DateField(default=date.today)
finalizado = models.BooleanField(default=False)
qtd_parcela = models.IntegerField()
valor_parcela = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
preco_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
itens = models.ManyToManyField(Produto, related_name="pedidos", through="Ped_Pro")
class Ped_Pro(models.Model):
produto = models.ForeignKey(
Produto, on_delete=models.PROTECT, related_name="ped_pros"
)
pedido = models.ForeignKey(
Pedido, on_delete=models.PROTECT, related_name="ped_pros"
)
qtd_produto = models.IntegerField(default=1)
data_entrada = models.DateTimeField(default=datetime.now)
The serializers:
class ProdutoSerializer(ModelSerializer):
class Meta:
model = Produto
fields = "__all__"
class Ped_ProSerializer(ModelSerializer):
class Meta:
model = Ped_Pro
fields = "__all__"
class PedidoSerializer(ModelSerializer):
itens = Ped_ProSerializer(many=True, read_only=True)
class Meta:
model = Pedido
fields = "__all__"
Could you help me find a way to the solution?
Project link on Github
In class ped pro you have 2 times the same related name: ped_pros
I'm trying to list the values of FacilityAddressSerializer within the FacilitySearchSerializer. This is what i tried. I get all the values of the FacilitySearchSerializer but the values of the FacilityAddressSerializer are showing as Null:
serializers.py
class FacilityAddressSerializer(serializers.ModelSerializer):
class Meta:
model = FacilityAddress
fields = (
"id",
"PrimaryAddress",
"SecondaryAddress",
"City",
"RegionOrState",
"PostalCode",
"Geolocation",
"AddressInfo"
)
class FacilitySearchSerializer(serializers.ModelSerializer):
AddressInfo = FacilityAddressSerializer(source="fa")
class Meta:
model = Facility
fields = (
"id",
"Name",
"AddressInfo",
"ListingVerified",
"mainimage",
"AdministratorCell",
"Capacity",
"PriceRangeMin",
"PriceRangeMax",
)
read_only_fields = ("id", "Name", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "FeaturedVideo", "PriceRangeMin", "PriceRangeMax")
models.py
class Facility(models.Model):
Name = models.CharField(max_length=150, null=True, blank=False)
mainimage = models.ImageField(null=True, blank=True)
Capacity = models.IntegerField(null=True, blank=True)
TelephoneNumber = models.CharField(max_length=30, null=True, blank=True)
AdministratorCell = PhoneNumberField(null=True, blank=True)
PriceRangeMin = models.IntegerField(null=True, blank=True)
PriceRangeMax = models.IntegerField(null=True, blank=True)
class FacilityAddress(models.Model):
PrimaryAddress = models.CharField(max_length=150, null=True, blank=True)
SecondaryAddress = models.CharField(max_length=150, null=True, blank=True)
City = models.CharField(max_length=150, null=True, blank=True)
RegionOrState = models.CharField(max_length=50, null=True, blank=True)
PostalCode = models.CharField(max_length=30, null=True, blank=True)
Geolocation = models.CharField(max_length=30, null=True, blank=True)
AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')
It works after i added (many=True) next to the source=fa. I thought i didn't need that since i'm using foreign key fields and not manytomany fields but i guess i was wrong.
This is my models. What is the best approach?
OneToOneField allows to create only one comments for all time.
class Person(models.Model):
first_name = models.CharField(
max_length=512,
blank=True,
null=True,
)
last_name = models.CharField(
max_length=512,
blank=True,
null=True,
)
class Product(models.Model):
slug = SlugField()
name = NameField()
description = DescriptionField()
class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.OneToOneField(Person, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
# You can use 'unique_together' feature of model
class Product(models.Model):
slug = SlugField()
name = NameField()
description = DescriptionField()
class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
class Meta:
unique_together = ("person", "product")
What you want is multiple comments per User, and multiple comments per Product. However, you need to ensure uniqueness for users and products inside comments. This can be achieved using unique_together (see https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together):
class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
class Meta:
unique_together = ['person', 'product']
I believe you need to add Product to Comment as well:
class Comment(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
text = models.TextField(null=True, blank=True)
class Meta:
unique_together = ['person', 'product']
How to solve this error? cause
whenever I search the student user I received an error,
error
admin.py
#admin.register(StudentsEnrollmentRecord)
class StudentsEnrollmentRecordAdmin(admin.ModelAdmin):
#inlines = [InLineSubject]
list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year')
#list_select_related = ('Student_Users')
ordering = ('Education_Levels','Student_Users__lrn')
list_filter = ('Student_Users','Education_Levels','Section','Payment_Type')
search_fields = ('Student_Users',)
def lrn(self, obj):
return obj.Student_Users.lrn
my models.py
class StudentsEnrollmentRecord(models.Model):
Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True)
School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True)
Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True)
UPDATE models
class StudentProfile(models.Model):
lrn = models.CharField(max_length=500,null=True)
Firstname = models.CharField(max_length=500,null=True,blank=True)
Middle_Initial = models.CharField(max_length=500,null=True,blank=True)
Lastname = models.CharField(max_length=500,null=True,blank=True)
Education_Levels= models.ForeignKey(EducationLevel, on_delete=models.CASCADE,blank=True,null=True)
You need to provide a specific field from StudentProfile - currently your search field is
search_fields = ('Student_Users',)
which means only the model itself. You didn't post a schema of your StudentProfile, but for example if it contains a Lastname field, you should use it like this:
search_fields = ('Student_Users__Lastname',)
To include multiple fields you can do
search_fields = ('Student_Users__Lastname', 'Student_Users__Firstname',)
You could also do
search_fields = ('=Student_Users__Lastname',)
to match the last name "exactly", previous example checks whether the field contains the query string
Data import using django-import-export is failing for m2m relationships.
The transaction doesn't generate any errors, however when trying to update an object's m2m relationship none of the updated values for m2m are being updated.
models.py
class Category(MPTTModel):
name = models.CharField(max_length=155, verbose_name=_('Category'))
code = models.CharField(max_length=255, verbose_name=_('Category Code'), help_text='primary key value for category', db_index=True)
categorytype = models.ForeignKey(ProductType, related_name='categories_for', verbose_name=_('Product type'), blank=True, null=True)
meta_description = models.TextField(verbose_name=_('Meta Description'))
meta_keywords = models.TextField(verbose_name=_('Meta Keywords'))
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
slug = models.SlugField(blank=True, verbose_name=_('URL alias'))
order = models.PositiveIntegerField()
class Product(models.Model):
reference = models.CharField(max_length=50, verbose_name=_('Reference'), db_index=True)
name = models.CharField(max_length=255, verbose_name=_('Product Name'))
description = models.TextField(blank=True, verbose_name=_('Product Description'))
specs = models.TextField(blank=True, verbose_name=_('Product Specifications'))
color_code = models.ForeignKey(ColorCode, verbose_name=_('Color Code'), related_name='colorcode_for')
color_web = models.CharField(max_length=7, verbose_name=_('Web Color'), db_index=True)
size = models.CharField(max_length=11, verbose_name=_('Product Size'))
price = models.IntegerField(verbose_name=_('Product Price'))
price_promo = models.IntegerField(blank=True, null=True, verbose_name=_('Product Promo Price'))
upc = models.CharField(max_length=155, verbose_name=_('UPC'))
stock = models.IntegerField(verbose_name=_('Product Stock'))
categories = models.ManyToManyField(Category, verbose_name=_('Estilo'), related_name='products')
in_stores = models.BooleanField(default=True, verbose_name=_('Product Availability'), db_index=True)
try_out = models.BooleanField(default=False, verbose_name=_('Try out Product'))
pub_date = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
slug = models.SlugField(default='', blank=True, verbose_name=_('URL alias'))
blog = models.URLField(blank=True, verbose_name=_('Blog mention link'))
parent_product = models.BooleanField(default=False, verbose_name=_('Main Product'), db_index=True)
main_product = models.ForeignKey('Product', blank=True, null=True, related_name='child_product')
active = models.BooleanField(default=True, verbose_name=_('Active'), db_index=True)
trends = models.ManyToManyField(Trends, verbose_name=_('Trends'), blank=True, related_name="trends")
photoshoot_id = models.CharField(max_length=255, verbose_name=_('Photoshoot ID'), blank=True)
new_arrival = models.BooleanField(default=False, db_index=True)
resources.py
class ProductResource(resources.ModelResource):
categories = fields.Field(widget=widgets.ManyToManyWidget(Category, separator="/"))
def export(self, queryset=None):
queryset = Product.objects.all()
headers = self.get_export_headers()
data = tablib.Dataset(headers=headers)
for obj in queryset.iterator():
data.append(self.export_resource(obj))
return data
class Meta:
model = Product
fields = ('categories', 'reference', 'name_es', 'name_en', 'description_es', 'description_en', 'specs_es', 'specs_en', 'color_code', 'color_web', 'size', 'price_es', 'price_en', 'price_promo_es', 'price_promo_en', 'upc', 'stock', 'in_stores', 'try_out', 'blog', 'active', 'photoshoot_id')
import_id_fields = ['upc']
skip_unchanged = True
Issue was fixed removing the skip_unchanged meta option, the skip_rowmethod in the ModelResource class is not reading the new value assigned in the .CSV