Disable option charField choices depending on another atribute (Django) - python

So, I have the following in my models.py:
UNITY_CHOICES = (
('g', 'Gram(s)'),
('kg', 'Kilogram(s)'),
('l', 'Liter(s)'),
('cl', 'Centiliter(s)'),
)
class Recipe_Ingredient(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
quantity = models.FloatField()
cost = models.DecimalField(max_digits=20, decimal_places=2)
quantityUnit = models.CharField(
max_length=2,
choices=UNITY_CHOICES,
default=GRAM,
)
class Ingredient(models.Model):
name = models.CharField(max_length=200)
articleNumber = models.IntegerField(unique=True)
costPrice = models.DecimalField(max_digits=20, decimal_places=2)
costAmout = models.FloatField()
costUnity = models.CharField(
max_length=2,
choices=UNITY_CHOICES,
default=GRAM,
)
And I have a simple form to add this model to my database:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit', 'ingredient')
So I was wondering if there's a way of filtering the quantityUnit available choices depending on the ingredient chosen.
I'll try to make it clear by an example: Let's say I choose to add Potato and the costUnity for Potato is 'g', then I want to make 'kg' and 'g' the only choices for quantityUnit. Is that a good example? I can try to think of something better if it's not clear enough.
Anyway, is it possible to do such thing? Thanks.
UPDATE:
forms.py:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit', 'ingredient')
template:
{% extends 'recipe/base.html' %}
{% block content %}
<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
Rendered HTML:
<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form"><input type="hidden" name="csrfmiddlewaretoken" value="tXVR3NM1R4TBwOJArWWClL71r8S5C18gWKz9mKK42wlEamf6NcBjzrieF5dQBOaO">
<p>
<label for="id_quantity">Quantity:</label>
<input type="number" name="quantity" required="" id="id_quantity" step="any">
</p>
<p>
<label for="id_quantityUnit">QuantityUnit:</label>
<select name="quantityUnit" id="id_quantityUnit">
<option value="g" selected="">Gram(s)</option>
<option value="kg">Kilogram(s)</option>
<option value="l">Liter(s)</option>
<option value="cl">Centiliter(s)</option>
</select>
</p>
<p>
<label for="id_ingredient">Ingredient:</label> <select name="ingredient" required="" id="id_ingredient">
<option value="" selected="">---------</option>
<option value="1">Carrot</option>
<option value="2">Potato</option>
<option value="3">Water</option>
<option value="4">Juice</option>
</select>
</p>
<button type="submit" class="save btn btn-default">Save</button>
</form>

Related

how to save foreign key from django html template

I want to save data from html template select field in django.
html example code:
<label for="type" style="color:red;">Short Name *</label>
<input type="text" name="short_name" class="form-control" required placeholder="">
<br> <br>
<select style='bakground-color:red' name="category" required class="form-control show-tick">
<option value="" selected="selected">---------</option>
{% for cat in category %}
<option value="{{ cat }}">{{ cat }}</option>
{% endfor %}
</select>
Django code:
Views.py
def addBooks(request):
template = 'admin_panel/add_books.html'
category = Category.objects.all()
book_details = BookDetails.objects.all()
context = {
"page_title": "Add Book",
"category": category,
"book_details" :book_details,
}
if request.method == "POST":
short_name = request.POST.get('short_name', None)
category = request.POST.get('category',None)
book_details = BookDetails.objects.create(short_name=short_name, category=category)
return render(request, template,context)
models.py
class BookDetails(models.Model):
id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=50, unique=True, db_index=True)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE
)
Error Showing:
ValueError at /superadmin/add_books/
Cannot assign "'Story'": "BookDetails.category" must be a "Category" instance.
How to solve this problem?
In tamplate
option value={{cat.id}}
In view:
BookDetails.objects.create(short_name=short_name, category_id=category)

Add product according to category in Django

I am new in Django. I want to add product against the category which I select, but I don't know how can I do that. I select the category and add product but nothing happened. I don't know how can I do this. Thank you in advance
Model.py
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
price = models.IntegerField()
view.py
class SelectCategory(TemplateView):
template_name = 'purchase/selectCategory.html'
def get(self, request, *args, **kwargs):
categories = CategoryModel.objects.all()
args = {'categories': categories}
return render(request, self.template_name, args)
def post(self, request):
try:
data = self.request.POST.get
categoryId = ProductModel.category['category.id'].id
product = ProductModel(
category_id=data(categoryId),
name=data('name'),
price=data('price')
)
product.save()
return redirect('menu')
except Exception as e:
return HttpResponse('failed{}'.format(e))
Template
{% extends 'auth/home.html' %}
{% block content %}
<form method="get">
{% csrf_token %}
<label> Select Category
<select name="Select Category">
<option disabled="disabled" selected> Select Category</option>
{% for category in categories %}
<option value={{ category.id }}>
{{ category.name }}
</option>
{% endfor %}
</select>
</label>
<input type="submit" value="Select">
</form>
<form method="post">
{% csrf_token %}
<label for="name">Name
<input type="text" name="name" id="name" placeholder="Enter Product name">
</label>
<label for="price">Price
<input type="number" name="price" id="price" placeholder="Enter Price of Product">
</label>
<button type="submit">Submit</button>
<button>Menu</button>
</form>
{% endblock %}
Get the category instance first using data selected category id and then push that instance to as a parameter to productmodel.
def post(self, request):
try:
data = self.request.POST.get
categoryObj= CategoryModel.objects.get(I'd=data[])
product = ProductModel(
category_id= categoryObj
name=data('name'),
price=data('price')
)
product.save()
return redirect('menu')
except Exception as e:
return HttpResponse('failed{}'.format(e))

how can I filter the difference between the two models? using django

I have 2 models, Product and ProductRelatedGroupAndProduct , the Product have 5 data, [chicken, okra, ampalaya, cabbage] and the ProductRelatedGroupAndProduct have [chicken, okra, cabbage] how do i get the remaining data in Product that dont have in ProductRelatedGroupAndProduct ?
the choosen product is ProductRelatedGroupAndProduct and the list of product is Product
I just want that the data displayed on the choosen product should no longer be visible in the product list.
so far this is my views.py
def searchrelatedproduct(request):
id = request.GET.get('relatedproductID')
products = Product.objects.all()
relatedproduct = ProductRelatedGroupAndProduct.objects.filter(productrelatedgroup = id)
return render(request, "customAdmin/relatedproduct.html",{"products":products,"relatedproduct":relatedproduct})
this is my html
<div class="container">
<form method="POST" action="/GroupOfProduct/" enctype="multipart/form-data">{% csrf_token %}
<h2>Product </h2>
<div class="form-group">
<br>
<label for="sel2">List Of Products</label>
<select multiple class="form-control" id="sel2" name="product">
{% for product in products %}
<option>{{product.product}}</option>
{% endfor %}
</select>
</div>
<input type="submit" style="float:right;">
</form>
</div>
<div class="container">
<h2>Choosen Product</h2>
<form method="POST" action="/UpdateGroupOfProduct/" enctype="multipart/form-data">{% csrf_token %}
<input type="submit" style="float:right;">
<div class="form-group">
<br>
<label for="sel2">List Of Choosen Products</label>
<select multiple class="form-control" id="sel2" name="relatedproduct">
{% for product in relatedproduct %}
<option value="{{ product.id }}">{{product.product}}</option>
{% endfor %}
</select>
</div>
</form>
</div>
this is my models.py
class ProductRelatedGroupAndProduct(models.Model):
product = models.ForeignKey(Product,on_delete=models.SET_NULL, null=True,blank=True,verbose_name="Product")
productrelatedgroup = models.ForeignKey('ProductGroup',
on_delete=models.SET_NULL, null=True, blank=True,
verbose_name="ProductGroup")
class Product(models.Model):
product = models.CharField(max_length=500)
class ProductGroup(models.Model):
category = models.CharField(max_length=500, blank=True)
UPDATE
when i tried this
diffproducts = products.exclude(pk__in=relatedproduct)
print(diffproducts)
it prints all data of the Product
<QuerySet [<Product: cabbage>, <Product: ampalaya>, <Product: okra>, <Product: Chicken>]>
and when i tried this
unused_product = set(relatedproduct).difference(set(products))
print(unused_product)
***result***
{<ProductRelatedGroupAndProduct: cabbage>, <ProductRelatedGroupAndProduct: ampalaya>, <ProductRelatedGroupAndProduct: okra>}
and this
Product.objects.filter(productrelatedgroupandproduct__isnull=True)
i get this error
django.core.exceptions.FieldError: Cannot resolve keyword 'productrelatedgroupandproduct' into field
You can use reverse relation for filter:
Product.objects.filter(productrelatedgroupandproduct__isnull=True)
productrelatedgroupandproduct here is a lowercased name of ProductRelatedGroupAndProduct model. It's default value for related_query_name argument.
This could be possible by converting your queryset to a set and then use intersection for complex cases.
# get objects present in both
set(products).intersection(set(relatedproduct))
# get product not in relatedproduct
set(products).difference(set(relatedproduct))
# opposite
set(relatedproduct).difference(set(products))
In your case exclude can do the trick:
products.exclude(pk__in=relatedproduct)
You can use the exclude function :
views.py:
def searchrelatedproduct(request):
id = request.GET.get('relatedproductID')
products = Product.objects.all()
relatedproduct = ProductRelatedGroupAndProduct.objects.filter(pk=id)
diffproducts = products.exclude(pk__in=relatedproduct)
return render(request, "test.html",{"products":diffproducts,"relatedproduct":relatedproduct})
and output in template in your orignal html.

django form field referencee from other model

I have a form that needs references from another model. here the example.
I have models.py
class Employee(models.Model):
name = models.CharField(max_length=100)
class Inven(models.Model):
name = models.CharField(max_length=255)
sn = models.DecimalField(max_digits=20, decimal_places=0)
employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='employee')
here my views.py
class InventoryListView(ListView):
context_object_name = 'inventorys'
model = models.Inventory
and here my inven template_form.html
<input type="text" name="name" maxlength="100" required="" id="id_name">
<input type="text" name="sn" maxlength="100" required="" id="id_sn">
<select>
{% for employee in employees %}
<option value="{{employee.pk}}">{{employee.name}}</option>
{% endfor %}
</select>
how to make employee field as a select list from employee model?...

Django Templates and drop-down list

I would like to render a Django form in the following manner...
Form UI
In particular, how would I go about populating and rendering the three drop-down lists based on the model provided.
The model
class Positions(models.Model):
position_code = models.CharField(primary_key=True, max_length=8)
name = models.CharField(max_length=64, blank=True, null=True)
description = models.CharField(max_length=4000, blank=True, null=True)
position_type = models.CharField(max_length=8, blank=True, null=True)
class Meta:
managed = False
db_table = 'positions'
class Clubs(models.Model):
club_id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=4, blank=True, null=True)
club_name = models.CharField(max_length=4000, blank=True, null=True)
nickname = models.CharField(max_length=4000, blank=True, null=True)
class Meta:
managed = False
db_table = 'clubs'
class Players(models.Model):
player_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=512, blank=True, null=True)
last_name = models.CharField(max_length=512, blank=True, null=True)
dob = models.CharField(max_length=512, blank=True, null=True)
display_name = models.CharField(max_length=512, blank=True, null=True)
active = models.BooleanField(default=True)
class Meta:
managed = False
db_table = 'players'
class DefaultSquads(models.Model):
default_squad_id = models.AutoField(primary_key=True)
club = models.ForeignKey(Clubs, models.DO_NOTHING)
player = models.ForeignKey('Players', models.DO_NOTHING)
position_code = models.ForeignKey('Positions', models.DO_NOTHING, db_column='position_code', blank=True, null=True)
playing_status_code = models.CharField(max_length=16, blank=True, null=True)
class Meta:
managed = False
db_table = 'default_squads'
The view
class DefaultSquadsViewCreate(CreateView):
template_name = 'fafl/defaultSquad_form.html'
model = DefaultSquads
fields = ['player', 'position_code', 'playing_status_code']
success_url = reverse_lazy('fafl:defaultSquads-list')
def get_context_data(self, **kwargs):
context = super(DefaultSquadsView, self).get_context_data(**kwargs)
context['clubs'] = Clubs.objects.all().order_by('club_id')
context['players'] = Players.objects.all().order_by('player_id')
return context
The template
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="box-body">
<div class="form-group">
<label for="{{ form.club.club_id.id_for_label }}" class="col-sm-2 control-lable">Club</label>
<div class="col-sm-10">
<!-- Not sure how ? -->
<select id="{{ form.club.club_id.id_for_label }}" name="club" class="form-control">
<option value="None"></option>
{% for club in clubs %}
<option value="{{ club.club_id }}" selected="selected">{{ club.nickname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.club_name.id_for_label }}" class="col-sm-2 control-lable">Player</label>
<div class="col-sm-10">
<input id="{{ form.short_name.id_for_label }}" type="text" name="short_name" maxlength="100" class="form-control" required />
</div>
</div>
<div class="form-group">
<label for="{{ form.club_name.id_for_label }}" class="col-sm-2 control-lable">Position</label>
<div class="col-sm-10">
<input id="{{ form.nickname.id_for_label }}" type="text" name="nickname" maxlength="6" class="form-control" required />
</div>
</div>
</div>
<div class="box-footer">
<div class="margin">
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" data-target="#myModal"><i class="fa fa-trash" role="button"></i> Delete</button>
Cancel
<button type="submit" class="btn btn-success"><i class="fa fa-check" role="button"></i> Save</button>
</div>
</div>
</form>
Since your question was only directed to form rendering . . .
In the view:
class DefaultSquadsViewCreate(CreateView):
template_name = 'fafl/defaultSquad_form.html'
model = DefaultSquads
fields = ['player', 'position_code', 'playing_status_code']
success_url = reverse_lazy('fafl:defaultSquads-list')
def get_context_data(self, **kwargs):
context = super(DefaultSquadsView, self).get_context_data(**kwargs)
context['clubs'] = Clubs.objects.all().order_by('club_id')
context['players'] = Players.objects.all().order_by('player_id')
context['positions'] = Positions.objects.all()
return context
In the template:
<div class="form-group">
<label for="{{ form.club.id_for_label }}" class="col-sm-2 control-label">Club</label>
<div class="col-sm-10">
<select id="{{ form.club.id_for_label }}" name="{{ form.club.html_name }}" class="form-control">
<option value="" selected>None</option>
{% for club in clubs %}
<option value="{{ club.club_id }}">{{ club.nickname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.player.id_for_label }}" class="col-sm-2 control-label">Player</label>
<div class="col-sm-10">
<select id="{{ form.player.id_for_label }}" name="{{ form.player.html_name }}" class="form-control">
<option value="" selected>Please select a player</option>
{% for player in players %}
<option value="{{ player.player_id }}">{{ player.display_name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.postion_code.id_for_label }}" class="col-sm-2 control-label">Position Code</label>
<div class="col-sm-10">
<select id="{{ form.position_code.id_for_label }}" name="{{ form.position_code.html_name }}" class="form-control">
<option value="" selected>Please select a Position</option>
{% for position in positions %}
<option value="{{ position.position_code }}">{{ position.name }}</option>
{% endfor %}
</select>
</div>
</div>

Categories

Resources