I have this code:
class Reference(models.Model):
title = models.CharField(max_length=200, verbose_name = _('title'))
def __unicode__(self):
return u"%s" % (self.title)
class Meta:
verbose_name = _('bibliographic reference')
verbose_name_plural = _('bibliographic references')
class Relation(models.Model):
reference = models.ForeignKey(Reference)
circuit = models.ManyToManyField('Circuit', related_name = 'relation_circuit', verbose_name = _('Circuits'))
def __unicode__(self):
return u"%s " %(self.reference)
class Meta:
verbose_name = _('relation')
verbose_name_plural = _('relations')
class Circuit(models.Model):
name = models.CharField(max_length=200, verbose_name = _('name'))
reference = models.ManyToManyField(Relation, through=Relation.circuit.through, related_name='relation_circuit', verbose_name = _('Bibliographic References'))
def __unicode__(self):
return u"%s" % (self.name)
class Meta:
verbose_name = _('circuit')
verbose_name_plural = _('circuits')
Relation is shown as an inline in Reference.
I need to create a bidirectional relationship between my Circuits and the References, but I have no idea how to show all my References instead only those who had a Relation, cause Relation is between them.
Anybody can help me?
Thank you very much.
This would be my starting point.
class Reference(models.Model):
title = models.CharField(max_length=200)
relations = models.ManyToManyField('Relation', related_name="reference_relations", null=True, blank=True)
def __unicode__(self):
return u"%s" % (self.title,)
class Relation(models.Model):
reference = models.ForeignKey(Reference)
circuit = models.ForeignKey('Circuit')
def __unicode__(self):
return u"%s <-> %s " %(self.reference, self.circuit)
class Circuit(models.Model):
name = models.CharField(max_length=200)
relations = models.ManyToManyField(Relation, related_name="circuit_relations", null=True, blank=True)
def __unicode__(self):
return u"%s" % (self.name)
admin.py
from django.contrib import admin
from web.models import *
class RelationInline(admin.TabularInline):
model = Relation
class CircuitAdmin(admin.ModelAdmin):
inlines = [
RelationInline,
]
class ReferenceAdmin(admin.ModelAdmin):
inlines = [
RelationInline,
]
admin.site.register(Reference,ReferenceAdmin)
admin.site.register(Relation)
admin.site.register(Circuit, CircuitAdmin)
Of course you can do this without the through table, but my preference is to keep relations simple.
I'm not sure if I completely understood what you need, but wouldn't a table with a foreignKey to both be enough?
Something like
class Reference(models.Model):
title = models.CharField(max_length=200, verbose_name = _('title'))
class Circuit(models.Model):
name = models.CharField(max_length=200, verbose_name = _('name'))
class Relation(models.Model):
reference = models.ForeignKey(Reference)
circuit = models.ForeignKey(Circuit)
Then you can link them by creating an instance of Relation like so:
circuit = Circuit(name="cool_circuit")
reference = Reference(title="cool_reference")
relation = Relation(reference=reference, circuit=circuit)
It's also easy to get all references linked to some circuit
circuit = Circuit.objects.get(id=1)
references_linked_to_circuit_1 = Reference.objects.filter(relation__circuit=circuit)
and likewise for all circuits linked to a reference
reference = Circuit.objects.get(id=1)
circuits_linked_to_reference_1 = Reference.objects.filter(relation__reference=reference)
Related
I am learning Django so this is all very new to me. What I am trying to create is a bit of functionality in my admin panel that will allow me to create a layout like this.
Test
-Event1
--Property1
--Property2
--Property3
--Property4
-Event2
--Property1a
--Property2b
--Property3c
--Property4d
-Event3
--Property1aa
--Property2bb
--Property3cc
--Property4dd
-Event4
--Property1aaa
--Property2bbb
--Property3ccc
--Property4ddd
I want to have multiple tests. My current model setup looks like this:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
("string", "string"),
("integer", "integer"),
("array", "array"),
("boolean", "boolean")
)
class Test(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
class Meta:
verbose_name = 'Test'
verbose_name_plural = 'Tests'
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=255)
test_id = models.IntegerField()
class Meta:
verbose_name = 'Event'
verbose_name_plural = 'Events'
def __str__(self):
return self.name
class Property(models.Model):
name = models.CharField(max_length=255)
property_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
expected_value = models.CharField(max_length=255)
class Meta:
verbose_name = 'Property'
verbose_name_plural = 'Properties'
def __str__(self):
return self.name
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name', 'description']
I have my admin panel setup so that I can create multiple properties. But then when I go to the "Events" section in my admin panel I can only create events. I want to be able to pick the properties and add them to my event. Then I want to be able to go to the Test page and add the events to it.
A good example of what I am trying to create is a replica of this: http://jsonparser.tools/tests.php
you should define foreign keys for events and properties:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
("string", "string"),
("integer", "integer"),
("array", "array"),
("boolean", "boolean")
)
class Test(models.Model):
name = models.CharField(max_length=255)
description = models.CharField(max_length=255, blank=True)
class Meta:
verbose_name = 'Test'
verbose_name_plural = 'Tests'
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=255)
test = models.ForeignKey(Test,on_delete=models.CASCADE)
class Meta:
verbose_name = 'Event'
verbose_name_plural = 'Events'
def __str__(self):
return self.name
class Property(models.Model):
event = models.ForeignKey(Event,on_delete=models.CASCADE)
name = models.CharField(max_length=255)
property_type = models.CharField(max_length=20, choices=TYPE_CHOICES)
expected_value = models.CharField(max_length=255)
class Meta:
verbose_name = 'Property'
verbose_name_plural = 'Properties'
def __str__(self):
return self.name
class TestForm(ModelForm):
class Meta:
model = Test
fields = ['name', 'description']
this should solve your problem if not let me know happy to help.
I am writing one method in Django Manager model.
I want to write method that finds out number of all sold copies (books) per author.
I have two models and method written in Manager.
My problem is that method should also be chainable from any Author queryset, for example something like
Author.objects.filter(...).exlucde(...).total_copies_sold()
should also work.
Example:
author = Author.objects.create(...)
Book.objects.create(..., author=author, copies_sold=10)
Book.objects.create(..., author=author, copies_sold=20)
author_total_books = Author.objects.total_copies_sold().first()
>>> author_total_books.copies
30
Below my code. It works like in example above, but then I try something like:
author_books = Author.objects.filter(id=2).total_copies_sold()
I got
'QuerySet' object has no attribute 'annotate'
class AuthorManager(models.Manager):
def total_copies_sold(self):
return self.get_queryset().annotate(copies=Sum('book__copies_sold')
class Author(models.Model):
first_name = models.CharField(max_length=120)
last_name = models.CharField(max_length=120)
objects = AuthorManager()
class Book(models.Model):
title = models.CharField(max_length=120)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
[Edited]
Thank you schillingt for reply. I added:
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
return self.annotate(copies=Sum('books__copies_sold'))
I tried something like:
author_books = Author.objects.filter(id=2).total_copies_sold()
>>> author_books.copies
I got
'AuthorQueryset' object has no attribute 'copies'
What you are lookig for is :
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('books__copies_sold'))
class Author(models.Model):
objects = AuthorManager()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
Now it is possible to chain queries e.g.:
author_total_books = Author.objects.total_copies_sold().first()
However you will no be able to use it on QuerySet object like:
author_books = Author.objects.filter(id=2).total_copies_sold()
That is because you are annotating Author object, not a QuerySet. To obtain that result you should execute:
Author.objects.annotate_with_copies_sold().get(id=2)
author.copies_sold
15
You need to use Manager.from_queryset to set your manager. Here are the docs.
class AuthorQueryset(models.QuerySet):
def total_copies_sold(self):
...
class Author(models.Model):
objects = models.Manager.from_queryset(AuthorQueryset)()
from django.db import models
from django.db.models import Sum
from django.db.models.functions import Coalesce
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
# Write your solution here
return self.annotate(copies_sold=Coalesce(Sum('books__copies_sold'), 0))
class Author(models.Model):
# Make sure this manager is available.
objects = AuthorManager()
# objects = models.Manager.from_queryset(AuthorQuerySet)()
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
enter code here
class AuthorManager(models.Manager):
def get_queryset(self):
return AuthorQuerySet(self.model, using=self._db)
def annotate_with_copies_sold(self):
return self.get_queryset().annotate_with_copies_sold()
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Sum('Book_Author__copies_sold'))
class Author(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
objects = AuthorManager()
class Meta:
verbose_name_plural = "Author"
verbose_name = 'Author'
ordering = ('first_name','last_name')
class Book(models.Model):
title = models.CharField(max_length=250, unique=True)
copies_sold = models.PositiveIntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='Book_Author')
class Meta:
verbose_name_plural = "Book"
verbose_name = 'Book'
ordering = ('title','copies_sold')
from vehicles.models import Author, Book
try:
author = Author.objects.get(first_name='Mark', last_name='Twain')
except Author.DoesNotExist:
author = Author.objects.create(first_name='Mark', last_name='Twain')
try:
book = Book.objects.get(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Huckleberry Finn', copies_sold=7)
pass
try:
book = Book.objects.get(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
except Book.DoesNotExist:
book = Book.objects.create(author=author, title='Adventrure of Tomm Saywer', copies_sold=4)
pass
author = Author.objects.annotate_with_copies_sold().first()
print(author.copies_sold)
11
1.Create AuthorManager, AuthorQuerySet classes from Author and Books
2.Create Author, Book models
3.Prepare Test Data and use model manager to filter the queryset
Count books sold by authors using Django ORM
Wihtout writing custom manager you can use "AuthorQueryset" in Author Manager
Just a menthion AuthorQueryset.as_manager() in Author models, that's it.
Here are the Django Docs
from django.db import models
from django.db.models import Sum, Value
from django.db.models.functions import Coalesce
# Create your models here.
class AuthorQuerySet(models.QuerySet):
def annotate_with_copies_sold(self):
return self.annotate(copies_sold=Coalesce(Sum('books__copies_sold'),Value(0)))
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
objects = AuthorQuerySet.as_manager()
class Book(models.Model):
title = models.CharField(max_length=30)
copies_sold = models.PositiveIntegerField()
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name="books")
So I am trying to create an inline set similar to this image (http://oi48.tinypic.com/4gm5w2.jpg) so I can add multiple prices for different sizes for a product. I can't get it to even display the area in the django admin. On top of that by doing so I get the error:
<class 'apps.main.admin.PriceInline'>: (admin.E202) 'main.Apparel_Price' has no ForeignKey to 'main.Apparel_Price'.
models.py:
#python_2_unicode_compatible
class Apparel_Product(models.Model):
product_name = models.CharField(_("Name"), max_length=255)
default='media/None/no-img.jpg')
product_gender_type = models.CharField(max_length=256, choices=[('male', 'Male'), ('female', 'Female'), ('unisex', 'Unisex')])
product_brand = models.CharField(_("Brand"),max_length=25)
product_sizes = models.CharField(_("Sizes"),max_length=25)
product_colors = models.CharField(_("Colors"),max_length=25)
product_price = models.CharField(_("Price"),max_length=10)
product_description = models.CharField(_("Description"),max_length=500)
product_shipping_options = models.CharField(_("Shipping Options"),max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Apparel Product")
verbose_name_plural = _("Apparel Products")
def __str__(self):
return self.album_name
#python_2_unicode_compatible
class Apparel_Picture(models.Model):
master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
product_caption = models.CharField(_("Caption"), max_length=255)
product_photo = models.ImageField(_("Picture"), upload_to='media/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Picture")
verbose_name_plural = _("Pictures")
def __str__(self):
return self.photo_caption
#python_2_unicode_compatible
class Apparel_Price(models.Model):
# master_apparel_product = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
master_apparel_product = models.OneToOneField(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
product_price = models.CharField(_("Price"), max_length=255)
product_size = models.ForeignKey(Apparel_Product, verbose_name=_("Apparel Product"), on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("Price")
verbose_name_plural = _("Prices")
def __str__(self):
return self.product_price
admin.py:
from django.contrib import admin
from .models import Apparel_Product, Apparel_Picture, Apparel_Price
# Register your models here.
def get_picture_preview(obj):
if obj.pk: # if object has already been saved and has a primary key, show picture preview
return """<img src="{src}" alt="{title}" style="max-width: 200px; max-height: 200px;" />""".format(
src=obj.photo.url,
title=obj.photo_caption,
)
return ("(choose a picture and save and continue editing to see the preview)")
get_picture_preview.allow_tags = True
get_picture_preview.short_description = ("Picture Preview")
class PictureInline(admin.StackedInline):
model = Apparel_Picture
extra = 0
fields = ["get_edit_link", "product_caption", "product_photo", get_picture_preview]
readonly_fields = ["get_edit_link", get_picture_preview]
def get_edit_link(self, obj=None):
if obj.pk: # if object has already been saved and has a primary key, show link to it
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[force_text(obj.pk)])
return """{text}""".format(
url=url,
text=_("Edit this %s separately") % obj._meta.verbose_name,
)
return ("(save and continue editing to create a link)")
get_edit_link.short_description = ("Edit link")
get_edit_link.allow_tags = True
class PriceInline(admin.TabularInline):
model = Apparel_Price
extra = 0
fields = ["price",]
#admin.register(Apparel_Product)
class Apparel_ProductAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["product_name", "product_gender_type", "product_brand", "product_sizes", "product_colors", "product_price", "product_description", "product_shipping_options",]
inlines = [PictureInline]
#admin.register(Apparel_Picture)
class Apparel_PictureAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["master_apparel_product", "product_caption", "product_photo", get_picture_preview]
readonly_fields = [get_picture_preview]
#admin.register(Apparel_Price)
class Apparel_PriceAdmin(admin.ModelAdmin):
save_on_top = True
fields = ["master_apparel_product", "product_price",]
inlines = [PriceInline,]
So I am really confused how main.Apparel_Price would need a foreign key to itself. The one for the picture works but the one for the prices do not and I tried copying them and it didn't work. Help would greatly be appreciated.
PriceInline has model Apparel_Price same as Apparel_PriceAdmin. Just use PriceInline as inline in Apparel_ProductAdmin.
I can't get the my Router to filter my requests based on the "parents_query_lookup".
Here's my code:
urls.py:
from rest_framework_extensions.routers import ExtendedSimpleRouter
from .views import OrganizationViewSet, GroupViewSet, BootGroupViewSet
router = ExtendedSimpleRouter()
(router.register(r'organizations', OrganizationViewSet,
base_name='organization')
.register(r'groups', GroupViewSet, base_name='organizations-group',
parents_query_lookups=['resource__organization'])
.register(r'boot_groups', BootGroupViewSet,
base_name='organizations-groups-boot_group',
parents_query_lookups=['group__resource__organization', 'group']))
urlpatterns = router.urls
views.py:
from rest_framework.viewsets import ModelViewSet
from rest_framework_extensions.mixins import NestedViewSetMixin
from .models import Organization, OrganizationSerializer, \
Group, GroupSerializer, BootGroup, BootGroupSerializer
class OrganizationViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Organization.objects.all()
serializer_class = OrganizationSerializer
class GroupViewSet(NestedViewSetMixin, ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
class BootGroupViewSet(NestedViewSetMixin, ModelViewSet):
queryset = BootGroup.objects.all()
serializer_class = BootGroupSerializer
enums.py:
class ResourceTypeEnum:
RESOURCE_TYPE_GROUP = 'group'
RESOURCE_TYPE_VM = 'vm'
RESOURCE_TYPE_CHOICES = (
(RESOURCE_TYPE_GROUP, RESOURCE_TYPE_GROUP),
(RESOURCE_TYPE_VM, RESOURCE_TYPE_VM)
)
models.py:
from django.db.models import Model
from rest_framework.serializers import ModelSerializer
from .enums import ResourceTypeEnum
class Organization(Model):
organization_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', blank=True, null=True)
class Meta:
unique_together = (("name", "parent"))
verbose_name = "Organization"
verbose_name_plural = "Organizations"
app_label = 'api_manager'
db_table = 'organization'
def __unicode__(self):
return self.name
class OrganizationSerializer(ModelSerializer):
class Meta:
model = Organization
fields = ('name', 'parent')
depth = 2
class Resource(Model):
resource_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=55)
type = models.CharField(
max_length=5, choices=ResourceTypeEnum.RESOURCE_TYPE_CHOICES)
organization = models.ForeignKey(Organization)
class Meta:
verbose_name = "Resource"
verbose_name_plural = "Resources"
app_label = 'api_manager'
db_table = 'resource'
def __unicode__(self):
return self.name
class ResourceSerializer(ModelSerializer):
class Meta:
model = Resource
fields = ('name', 'type', 'organization')
depth = 2
class Group(Model):
resource = models.OneToOneField(Resource, primary_key=True)
is_consistent = models.BooleanField()
parent = models.ForeignKey('self', blank=True, null=True)
class Meta:
verbose_name = "Group"
verbose_name_plural = "Groups"
app_label = 'api_manager'
db_table = 'group'
def __unicode__(self):
return "%s: %s" % (self.resource.organization, self.resource)
class GroupSerializer(ModelSerializer):
class Meta:
model = Group
fields = ('resource', 'is_consistent', 'parent')
depth = 2
class BootGroup(Model):
boot_group_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
boot_order = models.PositiveSmallIntegerField(default=1)
group = models.ForeignKey(Group)
class Meta:
unique_together = (("boot_order", "group"))
verbose_name = "BootGroup"
verbose_name_plural = "BootGroups"
app_label = 'api_manager'
db_table = 'boot_group'
def __unicode__(self):
return "%s: %s" % (self.group.resource, self.name)
class BootGroupSerializer(ModelSerializer):
class Meta:
model = BootGroup
fields = ('name', 'boot_order', 'group')
depth = 2
class Vm(Model):
resource = models.OneToOneField(Resource, primary_key=True)
hostname = models.CharField(max_length=200, blank=True, null=True)
group = models.ForeignKey(Group, blank=True, null=True)
boot_group = models.ForeignKey(BootGroup, blank=True, null=True)
class Meta:
verbose_name = "Vm"
verbose_name_plural = "Vms"
app_label = 'api_manager'
db_table = 'vm'
def __unicode__(self):
return "%s: %s" % (self.resource.organization, self.resource)
class VmSerializer(ModelSerializer):
class Meta:
model = Vm
fields = ('resource', 'hostname', 'group', 'boot_group')
depth = 2
No matter what I try, something like "organizations/1/groups" returns all of the Group models, regardless of Organization. Am I missing something? Thanks in advance for the help.
Based on yours router definition, you need to define a queryset in GroupViewSet
from rest_framework_extensions.utils import compose_parent_pk_kwarg_name
def get_queryset(self):
resource_id = self.kwargs.get(compose_parent_pk_kwarg_name('resource_organization')
return Group.objects.filter(resource=resource_id)
The filter value can be find in kwargs as parent_lookup_<parents_query_lookups> or you can retrieve the parent query dict with self.get_parents_query_dict()
I just start to learn Django and I want to create a Product model with attributes, custom fields and custom field options. Custom field options exemple:
Line 1: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
Line 2: [YOUR TEXT] | Custom field options: [FONT] [FONT SIZE] [...]
So I've created this models:
from django.db import models
from django.utils import timezone
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
sku = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
price = models.DecimalField(max_digits=6, decimal_places=2)
active = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class ProductMeta(models.Model):
product = models.OneToOneField('Product')
title = models.CharField(max_length=100)
description = models.TextField(max_length=250)
class ProductImage(models.Model):
def upload_path(self, filename):
return 'static/uploads/images/%s%s' % (timezone.now().strftime('%Y/%m/%d/%Y%m%d_'), filename)
product = models.ForeignKey('Product')
name = models.CharField(max_length=100)
default = models.BooleanField()
image = models.ImageField(upload_to=upload_path)
def __unicode__(self):
return self.name
class ProductCharacteristic(models.Model):
product = models.ForeignKey('Product', related_name="characteristics")
name = models.CharField(max_length=100)
value = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttribute(models.Model):
category = models.ForeignKey('ProductAttributeCategory')
products = models.ManyToManyField('Product', related_name="attributes")
name = models.CharField(max_length=100)
ordering = ['-category']
def __unicode__(self):
return u'%s : %s' % (self.category, self.name)
class ProductAttributeCategory(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductAttributeValue(models.Model):
attribute = models.ForeignKey('ProductAttribute', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomField(models.Model):
product = models.ForeignKey('Product', related_name="custom_fields")
name = models.CharField(max_length=100)
description = models.TextField(max_length=250)
def __unicode__(self):
return self.name
class ProductCustomFieldOption(models.Model):
fields = models.ManyToManyField('ProductCustomField', related_name="options")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class ProductCustomFieldOptionValue(models.Model):
option = models.ForeignKey('ProductCustomFieldOption', related_name="values")
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
But now I don't know how to create the form in product details page in which the user can choose the product attributes (color, size...) and the product custom fields (and custom fields options). I've tried a lot of things but no results.
Can you help me please? :)
your question is unclear to me and your even more confusing. However see this if it helps
In your models.py
from django.db import models
from model_utils import Choices
colour_choices = ('Blue', 'Green')
class Product(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
reuturn self.name
class ProductAttributes(models.Model):
product = models.Foreignkey(Product, related_name='products')
colour = models.CharField(choices=Choices(*colour_choices))
In your forms.py
from django import forms
from .models import Product, ProductAttributes
class ProductForm(forms.ModelForm):
class Meta:
model = Product
class ProdductAttributesForm(forms.ModelForm):
class Meta:
model = ProductAttributes
Write your views.py, urls.py and template accordingly
this method will give you a text box to enter products and drop-down for choosing color.
Hope it helped!