Django form objects filter - django

I want to associate the drop-down lists material and category
models
class Demande_Expertise(models.Model):
user = models.ForeignKey(User)
material = models.ForeignKey("Material")
categorie = models.ForeignKey("Category")
class Category(models.Model):
name = models.CharField(_('name'), max_length=50)
slug = models.SlugField()
expert = models.ForeignKey(Expert, null=True, blank=True, default = None)
class Material(models.Model):
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
slug = models.SlugField()
category = models.ForeignKey(Category, verbose_name=_('category'))
forms
class Demande_ExpertiseForm(forms.ModelForm):
class Meta:
model = Demande_Expertise
def __init__(self, *args, **kwargs):
super(Demande_ExpertiseForm, self).__init__(*args, **kwargs)
self.fields['material'].queryset = Material.objects.filter(category=Category)
no error but filtering don't work.
how to filter name of the model Category?

You can filter a relation in a queryset by a field by using double underscores (so category__name in this case) and passing in whatever you want to filter it by.
class Demande_ExpertiseForm(forms.ModelForm):
class Meta:
model = Demande_Expertise
def __init__(self, *args, **kwargs):
super(Demande_ExpertiseForm, self).__init__(*args, **kwargs)
self.fields['material'].queryset = Material.objects.filter(category__name="name to filter")
In this case it will filter all of the Material objects to those which have a Category set to exactly name to filter. You can learn more by reading the Django documentation on retrieving objects.

Related

How can I filter products to show only those belonging to selected category in Django Admin?

I am trying to filter the options shown in a foreignkey field within Django Admin inline. Using formfield_for_foreignkey I'm able to show products with category_id = 4 but instead of the 4 I would like to filter based in the category field in the inline. Using kwargs["queryset"] = Product.objects.filter(category=F('order_line__category')) does not get the category field value.
class Order_lineInline(admin.StackedInline):
model = Order_line
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "product":
kwargs["queryset"] = Product.objects.filter(category=4)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
class Category(models.Model):
name = models.CharField(max_length=255)
class Product(models.Model):
part_number = models.CharField(max_length=255)
category = models.ForeignKey('Category')
price = models.DecimalField(max_digits=10, decimal_places=2)
class Order(models.Model):
customer = models.CharField(max_length=255)
class Order_line(models.Model):
order = models.ForeignKey('Order', on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
product = models.ForeignKey('Product', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
Maybe this is what you want:
Product.objects.filter(category__name='xxxxxx')

Set ManyToMany field in model save method

I have a problem, I try to save the model and only adds to 'members' the users that belong to the company set in the field 'company'.
This is my code:
class GroupFolderAccess(BaseModel):
name = models.CharField(max_length=128)
members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='belongs')
company = models.ForeignKey('Company', on_delete=models.CASCADE, related_name='folders')
folder = models.ForeignKey('recourse.Folder', null=True, blank=True, on_delete=models.CASCADE, related_name='get_group')
def save(self, *args, **kwargs):
for member in self.members.all():
if self.company != member.company:
print(member)
self.members.remove(member)
return super(GroupFolderAccess, self).save(*args, **kwargs)
When I save, it displays users correctly, but does not remove them from the relationship.

How to create an inline formset with manytomany relation in Django

I want to create an inline formset between Preorder model and Product model. The scenario is that the user will be able to select one or more than one products when he decides to create a preorder. On the other hand a product might be found in one or more than one preorders. With that in mind i created a manytomany relationship.
models.py
class Preorder(models.Model):
client = models.ForeignKey(Client,verbose_name=u'Client')
invoice_date = models.DateField("Invoice date",null=True, blank=True, default=datetime.date.today)
preorder_has_products = models.ManyToManyField(Product, blank=True)
def get_absolute_url(self):
return reverse('preorder_edit', kwargs={'pk': self.pk})
class Product(models.Model):
name = models.CharField("Name",max_length=200)
price = models.DecimalField("Price", max_digits=7, decimal_places=2, default=0)
barcode = models.CharField(max_length=16, blank=True, default="")
eopyy = models.CharField("Code eoppy",max_length=10, blank=True, default="")
fpa = models.ForeignKey(FPA, null=True, blank=True, verbose_name=u'Fpa Scale')
forms.py
class PreorderForm(ModelForm):
class Meta:
model = Preorder
exclude = ('client','preorder_has_products',)
def __init__(self, *args, **kwargs):
super(PreorderForm, self).__init__(*args,**kwargs)
self.fields['invoice_date'].widget = MyDateInput(attrs={'class':'date'})
class ProductForm(ModelForm):
#name = ModelChoiceField(required=True,queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='name-autocomplete'))
class Meta:
model=Product
fields = '__all__'
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['name'].label="Name"
self.fields['price'].label="Price"
and finally the inline formset:
PreorderProductFormSet = inlineformset_factory(Preorder, Product,
form=ProductForm, extra=1)
After run I face up the issue:ValueError at /
'intranet.Product' has no ForeignKey to 'intranet.Preorder'
Why this happening since I created a manytomany relation?
One solution is to create a foreign key relationship between Preorder and Product model inside Product model..but I do not want to do that since product model is used in other areas of my project and do not want to mess it up.
Any suggestions?

Use models foreign key _id column as field in django form

When you create a ForeignKey in a django model django also creates a _id column in the database. I'm trying to figure out how to display this value in a django form but can't seem to get it to work. With what I have below the category_id field appears in the form but the value itself doesn't?
marketplace/models.py
class Category(models.Model):
category = models.CharField(null=True)
category_code = models.IntegerField(unique=True)
store/models.py
class Product(models.Model):
created = models.DateTimeField(default=now)
name = models.CharField(max_length=200, unique=True)
category = models.ForeignKey('marketplace.Category', blank=True, null=True, to_field='category_code')
store/forms.py
class Form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
self.fields['category_id'] = self.instance.category_id
class Meta:
model = Product
fields = ['name', 'created']

How to implement a ordered many2many relation in the Django admin

Here a sample models I have:
class Category(models.Model):
name = models.CharField(max_length=128)
class Item(models.Model):
name = models,CharField(max_lenght=128)
category = models.ManyToManyField(Category, blank=True,
related_name='item_category',
null=True, through='ItemCategory')
class ItemCategory(models.Model):
item = models.ForeignKey(Item)
category = models.ForeignKey(Category)
order = models.PositiveIntegerField(default=0, blank=True, null=True)
My problem is how do I arrange the order in the admin side? In other words, I need to expand the widget functionality to allow the user to change the order of the selected items and when the form is saved, the selected items will save the item order in ItemCategory.order. I have the form that looks like this:
class CategoryForm(forms.ModelForm):
_items = forms.ModelMultipleChoiceField(
required=True,
label='Items',
queryset=Items.objects.all(),
widget=FilteredSelectMultiple(verbose_name="Items",
is_stacked=False)
)
def __init__(self, *args, **kwargs):
super(FamilyAdminForm, self).__init__(*args, **kwargs)
class Meta:
model = Items
You could use the Meta class:
class Category(models.Model):
# ...
class Meta:
ordering = ['name']