Reputation: 1246
I'm writing a form that a user can fill in in a browser. One of the questions involves selecting a number between 10000 and 100000. How would I go about prompting the user to do this? If they don't, I want a message to pop up in order to get them to actually pick a number between 10000 and 100000. The variable that deals with this particular figure is called borrowing. The data on the form is currently saved in a sqlite3 table.
Here is a my models.py:
from django.db import models
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
class User(models.Model):
#to store user data
firstname = models.CharField(max_length=100)
surname = models.CharField(max_length=100)
email = models.CharField(max_length=100)
telephone_number = models.CharField(max_length=15)
company_name = models.CharField(max_length=100)
company_street_address = models.CharField(max_length=100)
city = models.CharField(max_length=100)
postcode = models.CharField(max_length=10)
company_number = models.CharField(max_length=9)
filter_choices = (
('retail', 'Retail'),
('professional services', 'Professional Services'),
('food & drink', 'Food & Drink'),
('entertainment', 'Entertainment'),
)
business_sector = models.CharField(max_length=100, choices=filter_choices)
days = models.CharField(max_length=5)
reason_for_loan = models.CharField(max_length=2000)
#borrowing = models.IntegerField(choices=[(i, i) for i in range(1, 1)], blank=True)
#borrowing = models.IntegerField((validators=[MaxValueValidator(100),MinValueValidator(1)])
borrowing = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(100)])
if 10000 <= borrowing <= 100000:
#borrowing = models.CharField(max_length=100)
def __str__(self):
return self.firstname
As you can see I've tried a bunch of stuff with borrowing with no luck.
This is my forms.py:
from django import forms
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
class UserForm(forms.Form):
firstname = forms.CharField(max_length=100)
surname = forms.CharField(max_length=100)
email = forms.CharField(max_length=100)
telephone_number = forms.CharField(max_length=15)
company_name = forms.CharField(max_length=100)
company_street_address = forms.CharField(max_length=100)
city = forms.CharField(max_length=100)
postcode = forms.CharField(max_length=10)
company_number = forms.CharField(max_length=9)
filter_choices = (
('retail', 'Retail'),
('professional services', 'Professional Services'),
('food & drink', 'Food & Drink'),
('entertainment', 'Entertainment'),
)
business_sector = forms.ChoiceField(choices = filter_choices)
days = forms.CharField(max_length=5)
reason_for_loan = forms.CharField(max_length=2000,widget=forms.Textarea)
borrowing = forms.IntegerField(validators=[MinValueValidator(10000),MaxValueValidator(100000)])
## business_sector = forms.CharField(
## ('retail', 'retail'),
## ('professional_services', 'professional_services'),
## ('food_&_drink', 'food_&_drink'),
## ('entertainment', 'entertainment'))
This is my views.py:
from django.shortcuts import render
from users.forms import UserForm
from users.models import User
# the function executes with the signup url to take the inputs
def signup(request):
if request.method == 'POST': # if the form has been filled
form = UserForm(request.POST)
if form.is_valid():
# creating user data
user_obj = form.save()
return render(request, 'users/signup.html', {'user_obj': user_obj,'is_registered':True }) # Redirect after POST
firstname = request.POST.get('firstname', '')
surname = request.POST.get('surname', '')
email = request.POST.get('email', '')
telephone_number = request.POST.get('telephone_number', '')
company_name = request.POST.get('company_name', '')
company_street_address = request.POST.get('company_street_address', '')
city = request.POST.get('city', '')
postcode = request.POST.get('postcode', '')
company_number = request.POST.get('company_number', '')
form = request.POST.get('form', '')
business_sector = request.POST.get('business_sector', '')
borrowing = request.POST.get('borrowing', '')
days = request.POST.get('days', '')
reason_for_loan = request.POST.get('reason_for_loan', '')
user_obj = User(firstname=firstname, surname=surname, email=email,
telephone_number=telephone_number,company_name=company_name,
company_street_address=company_street_address,city=city,
postcode=postcode,company_number=company_number,
business_sector=business_sector,borrowing=borrowing,
days=days,reason_for_loan=reason_for_loan)
# saving all the data in the current object into the database
else:
form = UserForm() # an unboundform
return render(request, 'users/signup.html', {'form': form})
#the function executes with the showdata url to display the list of registered users
def showdata(request):
all_users = User.objects.all()
return render(request, 'users/showdata.html', {'all_users': all_users, })
This is my html:
<!-- The alert box to be shown when the submit button is clicked-->
{% if is_registered %}
<script>alert("You are successfully registered with your new business with:{{user_obj.company_name }} and Email: {{ user_obj.email }}")</script>
{% else %}
<form action="{% url 'users:signup' %}" method="post">
{% csrf_token %}
{{ form }}
<br />
<br />
<input type="submit" value="Submit">
</form>
{% endif %}
<br />
Upvotes: 0
Views: 164
Reputation: 12096
First of all you are not DRY at all!
You should use Django's ModelForm and you just made you life easier!
So, you should leave your models untouched (you may remove the validators
argument as well) and change the forms.py
to this:
# forms.py
from .models import User
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = '__all__'
def clean_borrowing(self):
borrowing = self.cleaned_data['borrowing']
if not 10000 < borrowing < 100000:
raise forms.ValidationError("Your error message here")
return borrowing
Finally in your views.py
save yourself some time and write:
# views.py
def signup(request):
# GET request. Create an unbound form
form = UserForm()
if request.method == 'POST': # if the form has been filled
form = UserForm(request.POST)
if form.is_valid():
# Form is valid. Because the Form (ModelForm) is bound to the User model, then it will create, save in db and return the instance automatically.
user_obj = form.save()
return render(request, 'users/signup.html', {'user_obj': user_obj,'is_registered':True }) # Redirect after POST
return render(request, 'users/signup.html', {'form': form})
Upvotes: 1
Reputation: 6106
You would put that kind of validation code in the form. Read the docs for more info.
For example:
class UserForm(forms.Form):
...
def clean_borrowing(self):
borrowing = self.cleaned_data['borrowing']
if not 10000 < borrowing < 100000:
raise forms.ValidationError("Please enter a borrowing value between " \
"10000 and 100000")
return borrowing
Upvotes: 1