社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

选择字段在html模板和django中提供两种不同的表单或不同的字段

Leo • 3 年前 • 1556 次点击  

我正在尝试为一名牙医和一名学生制作一份登记表,在这里我有一个牙医和一名学生的选择字段。我想做的是,当牙医被选中时,我应该能够看到 specialties 字段以及Django来选择该表单,学生也可以选择 student_email institution .我对如何在模板中编写代码感到困惑,我几乎到处都找遍了,找不到任何有助于我实现目标的东西。我还包括了一个注册图像的样子。我知道我可以用 select option 在html模板中,但仍然有点困惑。如果你能告诉我一个更好的方法来应用我的想法,请告诉我。

类型py

from django import forms
from django_countries.fields import CountryField


class RegistrationForm(forms.Form):

   Specialties = [
       ('pediatric','Pediatric'),
       ('oral surgeon','Oral Surgeon'),
       ('periodontist','Periodontist (Restorative; Esthetic)'),
       ('orthodontist','Orthodonsit'),
       ('endodontist','Endodontist'),
       ('prosthodontist','Prosthodontist'),
       ('oral pathologist','Oral Pathologist'),
       ('oral radiologist','Oral Radiologist'),
       ('public health dentist','Public Health Dentist'),
       ('research and academics','Research and Academics'),
   ]

   username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True, unique=True)
   email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True)
   student_email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True, unique=True)
   password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True)
   password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}), required=True)
   first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True)
   last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True)
   date_of_birth = forms.DateField(label = "Date of Birth", widget=forms.SelectDateWidget([x for x in range(1920,2021)]), required=True)
   country = CountryField().formfield(required=True)
   gender = forms.ChoiceField(widget=forms.RadioSelect, choices=[('male','Male'),('female','Female')], required=True)
   specialty = forms.CharField(widget=forms.Select(choices= Specialties), required=True)
   institution = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True)
   dentist_or_student = forms.ChoiceField(widget=forms.RadioSelect, choices=[('dentist','Dentsit'),('student','Student')], required=True)

   def clean_student_email(self):

       data = self.cleaned_data['student_email']
       if "@edu" not in data: #Check if the student's email is educational or not
           raise forms.ValidationError("Email must be @edu")
       return data

意见。py

def user_register(request):
    template_name = 'accounts/signup.html'

    if request.method == 'POST':
        
        form = RegistrationForm(request.POST)
        
        # Check for validity
        if form.is_valid():
            if form.cleaned_data['dentist_or_student'] == 'dentist':

                if User.objects.filter(username=form.cleaned_data['username']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Username already exists'
                    })
                elif User.objects.filter(email=form.cleaned_data['email']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Email already exists'
                    })
                elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                    return render(request,template_name, {
                        'form': form,
                        'error_message': 'Passwords do not match'
                    })
                else:
                    # Create the user
                    user = User.objects.create_user(
                        form.cleaned_data['username'],
                        form.cleaned_data['email'],
                        form.cleaned_data['password']
                    )
                    user.first_name = form.cleaned_data['first_name']
                    user.last_name = form.cleaned_data['first_name']
                    user.dentist_or_student = form.cleaned_data['dentist']
                    user.date_of_birth = form.cleaned_data['date_of_birth']
                    user.country = form.cleaned_data['country']
                    user.gender = form.cleaned_data['gender']
                    user.save()

                    # Login the user
                    login(request, user)

                    # redirect to Homepage
                    return HttpResponseRedirect('home')

            elif form.cleaned_data['dentist_or_student'] == 'student':
                if User.objects.filter(username=form.cleaned_data['username']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Username already exists'
                    })
                elif User.objects.filter(email=form.cleaned_data['student_email']).exists():
                    return render(request, template_name, {
                        'form': form,
                        'error_message': 'Email already exists'
                    })
                elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                    return render(request,template_name, {
                        'form': form,
                        'error_message': 'Passwords do not match'
                    })
                else:
                    # Create the user
                    user = User.objects.create_user(
                        form.cleaned_data['username'],
                        form.cleaned_data['student_email'],
                        form.cleaned_data['password']
                    )
                    user.first_name = form.cleaned_data['first_name']
                    user.last_name = form.cleaned_data['first_name']
                    user.dentist_or_student = form.cleaned_data['student']
                    user.date_of_birth = form.cleaned_data['date_of_birth']
                    user.country = form.cleaned_data['country']
                    user.gender = form.cleaned_data['gender']
                    user.save()

                    # Login the user
                    login(request, user)

                    # redirect to Homepage
                    return HttpResponseRedirect('home')

            else:
                messages.error(request, 'Please pick if either you are a Dentist or a Student before continuing the form')
                return redirect('register')

    # No post data available, just show the webpage
    else:
        form = RegistrationForm()

    return render(request, template_name, {'form': form})

enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128555
 
1556 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Paolo Vezzola
Reply   •   1 楼
Paolo Vezzola    3 年前

你应该把这两个都添加到你的html中,并把它们隐藏起来。 然后在Select中添加一个警报,一旦更改,就可以将所选表单设为hidden=false。

你自己选择。addEventListener(“更改”,document.getElementById(YOURSELECT.value)。删除属性(“隐藏”);

everspader
Reply   •   2 楼
everspader    3 年前

你正在使用 CharField ( see docs )对于具有选项的字段。尝试使用 ChoiceField ( 见文件 )相反。 比如:

specialty = forms.ChoiceField(choices= Specialties, required=True)