简体   繁体   English

Django,Python-如何创建一个用户只能选择10000到100000之间的数字的字段?

[英]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.

相关问题 如何在 python tkinter 中的两个输入字段编号之间创建一个随机数? - How can I create a random number between two entry field numbers in python tkinter? 如何使用 NumPy 在 Python 中快速填充 100000x100000 矩阵? - How can I quickly populate a 100000x100000 matrix in Python using NumPy? Django:如何过滤以仅返回已支付&gt; = 10000的那些候选人 - Django: How do i filter to return only those candidates that have paid >=10000 如何允许用户在两​​个选项之间进行选择? - How do I allow the user to choose between two options? 在Python中,如何根据用户输入的号码创建列表? - In Python, how do I create lists based on a user inputted number? 如何创建一个可变的时间函数,可以在python中选择时间(即不是实际的当前时间)? - How can I create a mutable time function where I can choose the time in python (i.e. not the actual current time)? 如何在Python 2.7中选择3个随机数? - How do I choose between 3 random numbers in Python 2.7? 如何创建在Python内部调用的R = 10000布尔值列表? - How can I create a list of R=10000 booleans called inside in Python? 如何使用打印语句创建菜单? 我希望能够选择一个数字,并根据我选择的数字运行该功能 - How do i create a menu using print statements? I want to be able to choose a number and based on what number i choose run that function 如何在 Django 中实现这个逻辑,卖家用户只能销售产品而买家只能购买产品? - How I can implement this logic in Django where seller user can only sale products and buyer can only buy product?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM