1

My page when requested through GET appears already with error "This field is required.", which is not a desirable behavior. I want this error appears when user actually attempts to submit a form without a data required.

This is my form Python class:

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)

Form's html:

<form action="{% url 'place_a_bid' listing.title %}">
                {% csrf_token %}
                <div class="form-row">
                    <div class="col">
                        {{ form }}
                    </div>
                    <div class="col">
                        <input class="btn btn-primary" type="submit" value="Place a bid">
                    </div>
                </div>
            </form>

And view:

def details(request, listing):
    listing_obj = Listing.objects.get(title=listing)
    form = Place_A_Bid_Form({"listing":listing_obj.title})
    categories = Category.objects.all()
    user = User.objects.get(username=request.user.username)
    if listing_obj in user.created_listings.all():
        return render(request, "auctions/details.html", {
            "listing": listing_obj,
            "categories": categories,
            "creator": True
        })
    elif listing_obj in user.watchlist.all():
        return render(request, "auctions/details.html", {
            "listing": listing_obj,
            "categories": categories,
            "in_watchlist": True,
            "form": form
            })
    else:
        return render(request, "auctions/details.html", {
            "listing": listing_obj,
            "categories": categories,
            "in_watchlist": False,
            "form": form
            })

What am I doing wrong? Thanks in advance.

Alex
  • 153
  • 7

1 Answers1

1

There is an error in that your form has no method, so it defaults to GET. It should be

<form action="{% url 'place_a_bid' listing.title %}" method="post">

Now why are you getting errors even if the form is not being submitted?

This form = Place_A_Bid_Form({"listing":listing_obj.title}) creates a bound form, which will give the error since bid is required and missing.

Perhaps what you intended is to create an unbound form with initial data, like this:

form = Place_A_Bid_Form(initial={"listing":listing_obj.title})

This will create the same looking form on your html, but since it's not bound, it will not give any errors, unless it is submitted with the missing bid field.

Check out the docs on bound and unbound forms, and this answer about how to provide initial data to each.

raphael
  • 2,469
  • 2
  • 7
  • 19