Issue
I want to make shure that the current value of the bid field
is not less than current biggest bid
. This is my form with a custom clean
method.
Form:
class Place_A_Bid_Form(forms.Form):
listing = forms.CharField(widget=forms.TextInput(attrs={"type":"hidden"}))
bid = forms.IntegerField(widget=forms.NumberInput(attrs={"class":"form-control"}), min_value=1)
def clean_bid(self, biggestBid):
bid = self.cleaned_data["bid"]
if bid < biggestBid:
raise ValidationError("""New bid shouldn't be less than starting bid, or
if any bids have been placed then new bid
should be greater than current biggest bid""")
return bid
View:
def place_a_bid(request):
if request.method == "POST":
form = Place_A_Bid_Form(request.POST)
user = User.objects.get(username=request.user.username)
biggest_bid = Bid.objects.filter(user=user).aggregate(Max("amount"))
if form.is_valid():
data = form.cleaned_data
user_obj = User.objects.get(username=request.user.username)
listing_obj = Listing.objects.get(title=data["listing"])
Bid.objects.update_or_create(
user=user_obj,
listing=listing_obj,
amount=data["bid"]
)
return redirect(listing_obj)
In view I am extracting current value that I am going to compare to, and I can't figure out how to pass this value to my form field's clean
method. Or maybe I'm doing this wrong? So how to do properly this sort of validation?
Solution
class Place_A_Bid_Form(forms.Form):
listing = forms.CharField(widget=forms.TextInput(attrs={"type":"hidden"}))
bid = forms.IntegerField(widget=forms.NumberInput(attrs={"class":"form-control"}),
min_value=1)
def __init__(self,biggestBid=0 *args, **kwargs):
super().__init__(*args, **kwargs)
self.biggestBid = biggestBid
def clean_bid(self):
bid = self.cleaned_data["bid"]
if bid < self.biggestBid:
raise ValidationError("""New bid shouldn't be less than starting bid, or
if any bids have been placed then new bid
should be greater than current biggest bid""")
return bid
and then in views.py:
def place_a_bid(request):
if request.method == "POST":
dict = Bid.objects.filter(user=user).aggregate(Max("amount"))
form = Place_A_Bid_Form(biggestBid=dict['amount__max'], data=request.POST)
user = User.objects.get(username=request.user.username)
if form.is_valid():
data = form.cleaned_data
user_obj = User.objects.get(username=request.user.username)
listing_obj = Listing.objects.get(title=data["listing"])
Bid.objects.update_or_create(
user=user_obj,
listing=listing_obj,
amount=data["bid"]
)
return redirect(listing_obj)
Answered By - eisa nahardani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.