I have a simple form and whenever the user does something wrong on the form I'd like to raise a validation error on Django. The problem is that I set up the form validation but when the form is submitted with wrong values, it goes through. I was wondering why it's happening and how I can avoid that?
Here is the html form:
<form id="ask-project" method="post" action="{% url 'ask-project' %}">
{% csrf_token %}
<input required="required" class="form-control form-text required" id="prenom" name="prenom" type="text">
<button class="btn btn-default submit">Submit</button>
</form>
views.py:
def askProject(request):
if request.method == 'POST':
form = AskProjectForm(request.POST)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
return redirect('/merci/') #success
forms.py:
class AskProjectForm(forms.ModelForm):
class Meta:
model = AskProject
fields = ['prenom']
def clean_prenom(self):
prenom = self.cleaned_data['prenom']
if len(prenom) < 3:
raise ValidationError('Votre prénom doit etre plus long que 1 caractère.')
return prenom
Am I doing something wrong?
With the pattern that you are using, this sort of problem is inevitable and order of the day. The first thing is not to render the form manually as you appear to be doing. That means you are not showing any feedback when the user enters invalid data. Consider using {{ form }}, {{ form.as_table }} etc or rendering the fields with all information as described here: https://docs.djangoproject.com/en/1.11/topics/forms/#rendering-fields-manually
Second problem is that you are redirecting when the form is submitted, regardless of whether it's valid or not. The recommended pattern is to redirect only when the form is valid. So even if you apply the suggestion in the first para, you are still not getting the required feedback. Consider implementing the form as suggested in the manual. A straight copy past follows
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Finally getting onto the specific case of why your form validation doesn't work, add a print statement in your clean method to print out both the string and it's length see if it tallies (or if your method even gets called)
Related
I am new to programming, I hope my question is not very basic. Here I am trying to taking the input and showing output on the same page.
I went through an article that said I should use GET method to do so.
my view
def calc(request):
if request.method == 'GET':
form = CalculationForm(request.GET)
if form.is_valid():
number1 = form.cleaned_data.get('first_number')
number2 = form.cleaned_data.get('second_number')
sum = number1 + number2
sum.save()
return render(request, 'calculation\calculator.html', {'sum': sum})
else:
form = CalculationForm()
return render(request, 'calculation\calculator.html', {'form': form})
my HTML
<body>
<form method="get" action=".">{% csrf_token %}
{{ form }}
<input type="submit" name="Register" value="Submit" />
{{sum}}
</body>
Here I am showing the user simple form
user input numbers in two fields
Add the numbers
showing it back to the user on the same page
My form is getting rendered and the fields are displaying I am able to enter the number in the field but when I click submit I get an error. Anyone
When you get an error, you should show it in your question, rather than just saying "I get an error".
The main issue here is that the request method is always GET, because that's how your form is being submitted. So your if statement is always true, even on first display of the page.
You need to switch on something else. One idea would be to use the fact that the Submit button is an input like the others, so would be included in the submitted data. So:
if 'Submit' in request.GET:
form = CalculationForm(request.GET)
...
Note that you will have another error, when you call sum.save(). The sum here is an integer, so it's not clear what you are trying to do when you call "save" on it.
I am using a django form in atemplate to save data entered to database.
In my view after the request is made, the response is redirected correctly but the data is not saved to db.
I might be missing something. but am unable to find it even after a lot of debugging.
here is what has been done so far:
views.py:
from .models import testmodel
def testview(request):
if request.method== 'POST':
form=MapForm(request.POST)
if form.is_valid():
test1=request.POST.get('t1')
print meaningid1
test2=request.POST.get('t2')
print meaningid2
pobj=testmodel(test1=test1,test2=test2)
pobj.save()
return HttpResponse('Successful')
after this the response message "Successful" is seen
from template:
<form action="/testview/" method="post"> {% csrf_token %}
{{form.as_p}}
<input type="text" name="t1" value='' id='t1'/> <br><br><br>
<input type="text" name="t2" value='' id='t2'/><br>
<input type="submit" value="Submit" />
</form>
from forms.py:
from .models import testmodel
class MapForm(forms.ModelForm):
class Meta:
model = testmodel
fields = ['test1','test2']
after the data is entered in form it is going to page /testview and showing message on page. but from backend data is not been saved to db.
Can some one suggest what could be done
Thanks
In python, indentation matters.
def testview(request):
if request.method== 'POST':
form=MapForm(request.POST)
if form.is_valid():
test1=request.POST.get('t1')
print meaningid1
test2=request.POST.get('t2')
print meaningid2
pobj=testmodel(test1=test1,test2=test2)
pobj.save()
return HttpResponse('Successful')
In the above code 'Successful' will be displayed regardless of whether the form is actually successful or not. You need to push your return statement four spaces to the right, and you also need to add an else clause which handles the situation where the form is not valid. Typically that is just to display the form again (with form errors which wil be displayed for you automatically is you use form.as_p or form.as_table)
I have such problem:
I have form, that displays on every page of a web-site. So, the action is for specified(separate) view:
def subscribe(request):
if request.method == "POST":
form = SubscriptionForm(data=request.POST)
if form.is_valid():
form.save()
return redirect() # there is a problem
else:
raise Http404
After success handling of form, I want to redirect a user to the page, from which form was sent.
But if I use request.path - it returns me an url that handles this form. But I need the url of a page...
Do you understand? What should I do?
Thanks a lot!
You'll need to add an additional field to your form to let your view know where to redirect to. The simplest way to do this is to add a hidden input to your form:
<form action="/some/url/" method="post">
...
<input type="hidden" name="next" value="{{ request.path }}">
</form>
The value of request.path is the path of the page before the user submits the form.
In your view, you can use the parameter next to redirect the user back to the page they came from.
def subscribe(request):
...
next = request.POST.get('next', '/some/default/url/here/')
return redirect(next)
I want to build a very simple webapp that takes a user's text, runs a function on it that alters it and then displays the altered text. I have the code for the function but everything else is unclear.
I am very new to django and just need a push in the right direction with this problem. At the very least, tell me what to google, I've went through several tutorials but neither of them dealt with this kind of task.
Thanks in advance!
Define a form; in forms.py under your app's folder
class MyForm(forms.Form):
myinput = forms.forms.CharField(max_length=100)
Define a function in your views.py
import .forms
def handle_form(request):
if request.method == 'POST': # If the form has been submitted...
form = MyForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = MyForm() # An unbound form
return render(request, 'handle_form.html', {
'form': form,
})
Add a template
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Of course you need to add it to your urls.py
Most info was copy pasted from: https://docs.djangoproject.com/en/1.8/topics/forms/
I'm during the form tutorial on https://docs.djangoproject.com/en/1.8/topics/forms/. I'm trying to make a simple form element, which will be POSTing some data. This is function launched in urls.py:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
HTML code looks as follows:
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
When I input some data to form and click 'Submit' button, function connected to /your-name/ URL is launched and I'm redirected to /your-name/. I'm wondering why function connected to /thanks/ URL is not launching. How can it be reached?
For the view to work, the form's action /your-name/ must be served by your view get_name.
You haven't shown your url patterns, so it's impossible to tell whether the mistake is there or not.