How to create products attributes like the one in django-shop - django-shop

I liked the way how django-shop is creating new products attributes by developping a product model. Ex: SmartPhone... I would like to add products attributes the same way but I do not know by where to start. By experience, when I am copying code from an app, I end up deleting the app as it doesn't work correctly.
My product model is:
`class Product(models.Model):
name = models.CharField('name', max_length=32)
slug = models.SlugField('slug', max_length=32)
description = models.TextField('description')
class Meta:
ordering = ['name']`
It would be great if you could advice me on how to add similar products attributes. This way I could create attributes like this example. I don't want to copy all the app because there is a lot of things that I don't need. [Smartcard example][1]https://github.com/awesto/django-shop/tree/master/example/myshop/models

First of all, you have to decide, whether you need a polymorphic approach or not. I assume your products do not vary that much, hence you don't need polymorphism.
Therefore something such as the smartcard example should be enough:
from shop.money.fields import MoneyField
from shop.models.product import BaseProduct, BaseProductManager, CMSPageReferenceMixin
from shop.models.defaults.mapping import ProductPage, ProductImage
class Product(CMSPageReferenceMixin, BaseProduct):
# common product fields
product_name = models.CharField(max_length=32)
slug = models.SlugField()
unit_price = MoneyField(decimal_places=3)
description = models.TextField("Description")
objects = BaseProductManager()

Related

Editing product page with dimsav/laravel-translatable

im using a package called Laravel-Translatable
but is giving me more problemns that i expect, mainly with quite simple tasks. For example i have a list of all records (products), and each of them haves 2 languages translated (en,es). But now i need to edit the product information to put in the inputs fields, and for this i wish in my edit page get all the translated details (title, description), but for some reason, is returning me only one language, it doesnt return all the translated details from a specific product:
ex: return Product::where('id', '2')->get();
Somebody uses this package?
Just read the documentation. Therein is all that you need.
Some example:
$product = Product::where('id', 2)->get();
$product->translate('de')->title = "Germany title";
$product->translateOrNew('pl')->title = "Polish title";
//Shortcut
$product->{'title:pl'} = 'lorem ipsum';
$product->save(); //It Will save all translations and main model

django-REST: Nested relationships vs PrimaryKeyRelatedField

Is it better to use nested relationships or PrimaryKeyRelated field if you have lots of data?
I have a model with deep relationships.
For simplicity I did not add the colums.
Model:
Usecase:
User creates 1 Workoutplan with 2 Workouts and 3 WorkoutExercises.
User creates 6 Sets for each WorkoutExercise/Exercise.
User starts workout > new FinishedWorkout is created
User does first exercise and enters the used weights > new FinishedWorkoutExercise with FinishedSet is created
Question:
I want to track the progression for each workoutplan > workout > exercise.
So with time the user may have finished dozens of workouts therefore hundreds if sets are already in the database.
If I now use nested Relationships I may load a lot of data I don't need.
But if I use PrimaryKeyRelatedFields I have to load all the data I need separately which means more effort in my frontend.
Which method is preferred in such a situation?
Edit:
If I use PrimaryKeyRelatedFields how do I distinguish if e.g. Workouts in Workoutplan is an array with primary keys or an array with the loaded objects?
If you use PrimaryKeyRelatedField, you'll have a big overload to request the the necessary data in frontend
In your case, I would create specific serializers with the fields you want (using Meta.fields attribute). So, you won't load unecessary data and the frontend won't need to request more data from backend.
I can write a sample code, if you need more details.
I'll get to the question regarding serializers in a second, but first of all and for clarification. What is the purpose of having duplicate models as Workout/Finished Workout, Set/Finished Set,...?
Why not...
class Workout(models.Model):
#...stuff...
finished = models.DateTimeField(null=True, blank=True)
#...more stuff...
Then you can just set a finished date on a workout when it's done.
Now, regarding the question. I would suggest you think about user interactions. What parts of the front-end are you trying to populate? How is the data related and how would the user access it?
You should think about what parameters you're querying DRF with. You can send a date and expect workouts finished on a specific day:
// This example is done in Angular, but you get the point...
var date= {
'day':'24',
'month':'10',
'year':'2015'
};
API.finishedWorkout.query(date).$promise
.then(function(workouts){
//...workouts is an array of workout objects...
});
Viewset...
class FinishedWorkoutViewset(viewsets.GenericAPIView,mixins.ListModelMixin):
serializer_class = FinishedWorkOutSerializer
queryset = Workout.objects.all()
def list(self, request):
user = self.request.user
day = self.data['day'];
month = self.data['month'];
year = self.data['year'];
queryset = self.filter_queryset(self.get_queryset().filter(finished__date=datetime.date(year,month,day)).filter(user=user))
page = self.paginate_queryset(queryset)
serializer = self.get_serializer(queryset, many=True)
return response.Response(serializer.data)
And then your FinishedWorkoutSerializer can just have whatever fields you want for that specific type of query.
This leaves you with a bunch of very specific URLs, which isn't all that great, but you can use specific serializers for those interactions and you're also open to dynamically changing the filter, depending on what paramaters are in self.data.
There is also a chance that you may want to filter differently depending what method is being called, say you want to list only active exercises, but if a user queries a specific exercise, you want him to have access to it (note that the Exercise object should have a models.BooleanField attribute called "active").
class ExerciseViewset(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
serializer_class = ExerciseSerializer
queryset = Exercise.objects.all()
def list(self, request):
queryset = self.filter_queryset(self.get_queryset().filter(active=True))
page = self.paginate_queryset(queryset)
serializer = self.get_serializer(queryset, many=True)
return response.Response(serializer.data)
Now you have different objects show up on the same URL, depending on the action. It's a bit closer to what you need, but you're still using the same serializer, so if you need a huge nested object on retrieve(), you're also gonna get a bunch of them when you list().
In order to keep lists short and details nested, you need to use different serializers.
Let's say you want to only send exercises' pk and name attributes when they are listed, but whenever an exercise is queried, you wan't to send along all related "Set" objects ordered inside an array of "WorkoutSets"...
# Taken from an SO answer on an old question...
class MultiSerializerViewSet(viewsets.GenericViewSet):
serializers = {
'default': None,
}
def get_serializer_class(self):
return self.serializers.get(self.action, self.serializers['default'])
class ExerciseViewset(MultiSerializerViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
queryset = Exercise.objects.all()
serializers = {
'default': SimpleExerciseSerializer,
'retrieve': DetailedExerciseSerializer
}
Then your serializers.py could look a bit like...
#------------------Exercise
#--------------------------Simple List
class SimpleExerciseSerializer(serializers.ModelSerializer):
class Meta:
model Exercise
fields = ('pk','name')
#--------------------------Detailed Retrieve
class ExerciseWorkoutExerciseSetSerializer(serializers.ModelSerializer):
class Meta:
model Set
fields = ('pk','name','description')
class ExerciseWorkoutExerciseSerializer(serializers.ModelSerializer):
set_set = ExerciseWorkoutExerciseSetSerializer(many=True)
class Meta:
model WorkoutExercise
fields = ('pk','set_set')
class DetailedExerciseSerializer(serializers.ModelSerializer):
workoutExercise_set = exerciseWorkoutExerciseSerializer(many=True)
class Meta:
model Exercise
fields = ('pk','name','workoutExercise_set')
I'm just throwing around use cases and attributes that probably make no sense in your model, but I hope this is helpfull.
P.S.; Check out how Java I got in the end there :p "ExcerciseServiceExcersiceBeanWorkoutFactoryFactoryFactory"

Mezzanine Forms Dropdown

I'm trying out Django/Mezzanine and if I have a custom user profile as such:
class UserProfile(models.Model):
user = models.OneToOneField("auth.User")
street_address1 = models.CharField(max_length=100)
street_address2 = models.CharField(max_length=100)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=32)
country = models.CharField(max_length=2)
phone = models.CharField(max_length=15)
Mezzanine creates a sign up form at account/signup/ and I would like to modify the Country field to have a drop down list of countries from a table or xml file. The foreign key is a two character field.
How should go about doing this? Do I create a model form or try to extend the right template (tried looking at accounts\templates\account_form.html but don't think it is there?
I believe if you defined a "choices" arg for the field, it'll do just that:
https://docs.djangoproject.com/en/dev/ref/models/fields/#choices
A quick Google search will probably also reveal some pre-built packages for country lists.

How to get attribute codes of super product attributes of a configurable product

For example, a configurable product with attributes Size and Color, I need to get the attribute codes of the above attributes.
or to be more specific, I need to know whether an attribute is used to configure a configurable product. I need this to check at product list page
try using this code
$config_product = Mage::getModel('catalog/product')->load($config_product_id);
$productAttributeOptions = $config_product->getTypeInstance(true)->getConfigurableAttributesAsArray($config_product);
Create an array as shown below:
$attributeValues['additional_options'][$count]['label'] = $aAttr['name'];
$attributeValues['additional_options'][$count]['value'] = $aAttr['value'];
Then pass the array while adding items to the order:
if (!empty($product['product_options'])) {
$orderItem->setProductOptions($product['product_options']);
}
Here $product['product_options'] is the array that we have created in the first step.

Magento - get results view HTML for a collection of products

I get a list of magento ids from a web service. I load these into and array $product_ids, so I have something like this:
Array
(
[0] => 1965
[1] => 3371
[2] => 1052
)
I can then make this into a collection:
$collection = Mage::getModel('catalog/product')->getCollection()
->addIdFilter($product_ids);
Using my Magento inspector, I've seen that the category pages use the class Mage_Catalog_Block_Product_List to display lists of products. I'd like to do something similar in my class. I've tried loading:
$ProductList = new Mage_Catalog_Block_Product_List();
$ProductList->setCollection($collection);
And then I've tried to load the HTML of the results as follows:
$CollectionHTML = $ProductList->_toHtml();
But $CollectionHTML is empty.
How would I get the HTML of what you see in the list view (i.e. the generated output of frontend/base/default/template/catalog/product/list.phtml, but given my collection)?
Making the code work the right way is much more easier in Magento than trying to work with ugly legacy code. I would gladly help you make the code the proper way when you have specific questions. Also, in the longterm, technical debt is gonna cost alot more.
Anyway, back to your issue.
In Magento block are not instantiated like in any app $myvar = new className ... almost never. This tutorial can help you understand better Magento's layout and blocks.
But if you want to create a block a way to do it is:
$block = Mage::getSingleton('core/layout')->createBlock('catalog/product_list')
Now related to your product collection you should check how Mage_Catalog_Block_Product_List::_getProductCollection actually works, because it uses the layered navigation, not a simple product collection.
Further, assuming that at least you are using a Magento controller and you are within a function, the following code will display the first page of products for a specified category:
//$category_id needs to be set
$layout = Mage::getSingleton('core/layout');
$toolbar = $layout->createBlock('catalog/product_list_toolbar');
$block = $layout->createBlock('catalog/product_list');
$block->setChild('toolbar', $toolbar);
$block->setCategoryId($category_id);
$block->setTemplate('catalog/product/list.phtml');
$collection = $block->getLoadedProductCollection();
$toolbar->setCollection($collection);
//render block object
echo $block->renderView();
Displaying specific ids:
you use root category id for $category_id variable (also make sure that display root category is set (or another category id that contains your product ids)
you can hook into catalog_block_product_list_collection event to add your ID Filter to the collection (this is called in _beforeToHtml function)
But, all this construction is not solid and there are still some points that require attention (other child blocks, filters and so on)

Resources