[英]Django, Python - How do I create a field where the user can only choose a number between 10000 and 100000?
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?
问题之一涉及选择一个介于10000和100000之间的数字。我将如何提示用户执行此操作? 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 .
如果没有,我希望弹出一条消息,以使他们实际选择10000到100000之间的数字。处理此特定数字的变量称为借款 。 The data on the form is currently saved in a sqlite3 table.
表单上的数据当前保存在sqlite3表中。
Here is a my models.py : 这是我的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 : 这是我的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 : 这是我的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 : 这是我的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 />
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
First of all you are not DRY at all! 首先,您根本不干 !
You should use Django's ModelForm and you just made you life easier! 您应该使用Django的ModelForm ,让生活更轻松!
So, you should leave your models untouched (you may remove the validators
argument as well) and change the forms.py
to this: 因此,您应该保持模型不变(也可以删除
validators
参数),并将forms.py
更改为:
# 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
节省一些时间并编写:
# 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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.