Datta Datta - 1 month ago 9
Python Question

How to load form with one value pre filled?

I'm using using Django forms to collect information from users. But when I change between pages I want to use one of the value from url to be displayed in a from in the next page.
Example.
I have url for checking out a book like
http://127.0.0.1:8000/checkout/780374157067

780374157067 is the ibn of the book

Next page has a form where I get the ISBN and card id of the user. How to fill the form with the ISBN and show the form to user. rather than the user giving the ISBN again.
enter image description here

ISBN Filed should be pre filled with thw isbn in URL.

HTML :

<div class ="col-md-3">
<form method='POST' action=''>{%csrf_token%}
{{template_form | crispy}}
<input class="btn btn-lg btn-primary" type='submit'
value='Submit'/>
</form>
</div>


Forms.py

class loansform(forms.Form):
Isbn = forms.IntegerField()
Card_id = forms.IntegerField()
def clean_Isbn(self):
isbn = self.cleaned_data.get("Isbn")
isbn_string = str(isbn)
if len(isbn_string) != 13:
raise forms.ValidationError("Enter a valid ISBN-13")
return isbn


views.py

template_form = loansform();

Answer

Say you've got url like

url(r'^checkout/(?P<isbn>\S+)/$')

In your view, when you instantiate form class, provide initial data to it like this.

form = YourFormClass(initial={'isbn': kwargs['isbn']})

kwargs contain url parameters, so you can get isbn from url.

Comments