Saya sedang menulis formulir yang dapat diisi pengguna di browser. Salah satu pertanyaan melibatkan pemilihan nomor antara 10.000 dan 100000. Bagaimana cara saya mendorong pengguna untuk melakukan ini? Jika tidak, saya ingin sebuah pesan muncul agar mereka benar-benar memilih angka antara 10.000 dan 100.000. Variabel yang berhubungan dengan angka khusus ini disebut meminjam. Data pada formulir saat ini disimpan dalam tabel sqlite3.

Ini adalah models.py saya:

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

Seperti yang Anda lihat, saya telah mencoba banyak hal dengan meminjam tanpa hasil.

Ini forms.py saya:

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'))

Ini adalah views.py saya:

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, })

Ini adalah html saya:

<!-- 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 />
0
semiflex 13 Maret 2017, 21:22

2 jawaban

Jawaban Terbaik

Pertama-tama Anda tidak KERING sama sekali!

Anda harus menggunakan ModelForm dan Anda baru saja membuat hidup Anda lebih mudah!

Jadi, Anda harus membiarkan model Anda tidak tersentuh (Anda juga dapat menghapus argumen validators) dan mengubah forms.py menjadi ini:

# 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

Akhirnya di views.py Anda menghemat waktu dan menulis:

# 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})
1
nik_m 14 Maret 2017, 07:05

Anda akan memasukkan kode validasi semacam itu ke dalam formulir. Baca dokumen untuk info lebih lanjut.

Sebagai contoh:

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
1
NS0 13 Maret 2017, 18:32