Reputation: 323
I don't know how to actually write the logic but I want to check user inputs especially price form field against Product model (price property).
I have model the django form as below:
class SalesForm(forms.ModelForm):
class Meta:
model = Sales
fields = ['product', 'customer', 'quantity', 'price']
Here is the Product Model
class Product(models.Model):
name = models.CharField(max_length=100, null=True)
category = models.CharField(max_length=100, choices=CATEGORY, null=True)
cost = models.PositiveIntegerField(null=True)
price = models.PositiveIntegerField(null=True)
quantity = models.PositiveIntegerField(null=True)
Here is what I am trying to do logically in views.py
def user_add_sales(request):
sales = Sales.objects.all().order_by('-salesdate')[:5]
if request.method == 'POST':
sales_form = SalesForm(request.POST)
if sales_form.is_valid:
sales_price = sales_form.cleaned_data('price')
try:
user_input = Product.objects.get(price = sales_price)
sales_form.save()
messages.success(request, 'Sales Added Successfully')
return redirect('dashboard-user-sales')
except user_input.DoesNotExist:
sales_form = SalesForm()
else:
sales_form = SalesForm()
context = {
'sales' : sales,
'sales_form' : sales_form,
}
return render(request, 'dashboard/user_sales.html', context)
When Try running the code, says 'SalesForm' object has no attribute 'cleaned_data'. Someone should please help me on how I can check whether what the user enters in price field of the SalesForm is not less than the price set for that product in Product Model.
Upvotes: 0
Views: 621
Reputation: 476659
The form is validated by the sales_form.is_valid()
method, not by an attribute, the if condition is thus:
if sales_form.is_valid():
# …
# …
In your form, you can check if the given price is at least the price in the related attribute with:
class SalesForm(forms.ModelForm):
# …
def clean(self, *args, **kwargs):
data = super().clean(*args, **kwargs)
if data['price'] < data['product'].price:
raise ValidationError('The price of the sale is below the price of the product')
return data
Upvotes: 2