如何使用正确的字段隐藏/显示我想要的表单
Posted
技术标签:
【中文标题】如何使用正确的字段隐藏/显示我想要的表单【英文标题】:How to hide / show the form that I want with the right fields 【发布时间】:2016-04-13 04:58:33 【问题描述】:嗨!我需要帮助,我想知道如何隐藏或显示表单。我有 2 个表单,一个 studentForm 和一个 EmployeeForm 当从下拉列表 profileType 中选择时,我希望她显示与所选 profileType 对应的表单
我不知道是我的 jQuery 不起作用还是为员工表单创建帐户不起作用。我不明白为什么它不起作用。我从数据库中获取表单字段的信息。**
我不知道为什么第二个按钮会出现此错误,因为第一个按钮运行良好并将信息保存在我的数据库中的正确字段中
为了完成,我有一个错误,因为在我的模板显示中,两个表单同时出现,只有第一个按钮 (Créer un compte)create an account 有效,而第二个用于 EmployeeForm 表单不起作用并返回错误 (我把错误的图片链接放在底部)
感谢您的宝贵时间和帮助!我被屏蔽了!
================================================ ==========================
这是我的models.py
from django.db import models
from django.utils import timezone
class Faculte(models.Model):
nom = models.CharField(max_length=30)
couleur = models.CharField(max_length=6)
def __str__(self):
return self.nom
class Personne(models.Model):
matricule = models.CharField(max_length=10)
nom = models.CharField(max_length=30)
prenom = models.CharField(max_length=30)
date_de_naissance = models.DateField()
courriel = models.EmailField()
tel_fixe = models.CharField(max_length=20,blank =True)
tel_mobile = models.CharField(max_length=20)
mot_de_passe = models.CharField(max_length=32)
amis = models.ManyToManyField("self",blank =True)
faculte = models.ForeignKey(Faculte)
def __str__(self):
return self.prenom + " " + self.nom
class Campus(models.Model):
nom = models.CharField(max_length=30)
adresse_postale = models.CharField(max_length=60)
def __str__(self):
return self.nom
class Fonction(models.Model):
intitule = models.CharField(max_length=30)
def __str__(self):
return self.intitule
class Cursus(models.Model):
intitule = models.CharField(max_length=30)
def __str__(self):
return self.intitule
class Employe(Personne):
bureau = models.CharField(max_length=30)
campus = models.ForeignKey(Campus)
fonction = models.ForeignKey(Fonction)
class Etudiant(Personne):
Cursus = models.ForeignKey(Cursus)
annee = models.IntegerField()
class Message(models.Model):
auteur = models.ForeignKey(Personne)
contenu = models.TextField()
date_de_publication = models.DateField()
def __unicode__(self):
if len(self.contenu) > 20:
return self.contenu[:19] + "..."
else:
return self.contenu
这是我的观点.py
from django.shortcuts import render, render_to_response, redirect
from django.http import HttpResponseRedirect
from polls.forms import LoginForm, StudentProfileForm, EmployeeProfileForm
from django.template import RequestContext
from django.http import HttpResponse
def welcome(request):
return render(request, 'polls/welcome.html')
def index(request):
return HttpResponse("Hello, world. You're at the webtrial index.")
def login(request):
if request.method=="POST":
form = LoginForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('polls/welcome')
else:
form= LoginForm()
return render(request, 'polls/login.html', 'form':form)
return render_to_response('polls/login.html', 'form': form,context_instance=RequestContext(request))
def register(request):
# if request.method=="GET":
if len(request.GET) > 0 and 'profileType' in request.GET:
studentForm = StudentProfileForm(prefix="st")
employeeForm = EmployeeProfileForm(prefix="em")
if request.GET['profileType'] == 'student':
studentForm = StudentProfileForm(request.GET, prefix="st")
if studentForm.is_valid():
studentForm.save(commit=True)
return HttpResponseRedirect('login/')
elif request.GET['profileType'] == 'employee':
employeeForm = EmployeeProfileForm(request.GET, prefix="em")
if employeeForm.is_valid():
employee.save(commit=True)
return HttpResponseRedirect('login/')
return render(request, 'polls/user_profile.html','studentForm': studentForm, 'employeeForm': employeeForm)
else:
studentForm = StudentProfileForm(prefix="st")
employeeForm = EmployeeProfileForm(prefix="em")
return render(request, 'polls/user_profile.html','studentForm': studentForm, 'employeeForm': employeeForm,)
这是我的 base.html
% load staticfiles %
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html>
% csrf_token %
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<title>Webtrial - % block title %Bienvenue !%endblock %</title>
</head>
<body id="% block bodyId %genericPage% endblock %">
<header>
% block headerContent %% endblock %
</header>
<section id="content">
% block content %
<head>
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<!-- //LIEN DU javascript ICI -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
% endblock %
</section>
</body>
</html>
这是我的 urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from polls import views
from polls.views import welcome, login, register
admin.autodiscover()
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^register/', views.register),
url(r'^login/',views.login),
url(r'^', views.login)
]
这是我的forms.py
from django import forms
from polls.models import Personne, Etudiant, Employe
class LoginForm(forms.Form):
email = forms.EmailField(label='Courriel')
password = forms.CharField(label='Mot de passe', widget = forms.PasswordInput)
def clean(self):
cleaned_data = super (LoginForm, self).clean()
email = cleaned_data.get("email")
password = cleaned_data.get("password")
if email and password:
result = Personne.objects.filter(mot_de_passe=password, courriel=email)
if len(result) != 1:
raise forms.ValidationError("Adresse de courriel ou mot de passe erroné(e).")
return cleaned_data
class StudentProfileForm(forms.ModelForm):
class Meta:
model = Etudiant
exclude =('amis',)
class EmployeeProfileForm(forms.ModelForm):
class Meta:
model = Employe
exclude = ('amis',)
这是我的 user_profile.html(表单和 jquery 所在的位置)
% extends "polls/base.html" %
% block title %Création d'un profil% endblock %
% block bodyId %userProfilePage% endblock %
<!-- <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> -->
<script type="text/javascript">
$("#column_select").change(function()
if($("#profilType").val() == "student")
$('#employeeForm').hide();
$('#studentForm').show();
else
$('#studentForm').hide();
$('#employeeForm').show();
$(document).ready(function())
);
</script>
% block content %
<h1>Création d'un compte</h1>
<form>
<p>
<label for="profileType">Vous êtes :</label>
<select name ="profileType" id="profilType">
<option value="student">Etudiant</option>
<option value="employee">Employe</option>
</select>
</p>
</form>
<div id="studentForm" class="student">
<form action="register" method="GET" id="studentForm">
studentForm.as_p
% csrf_token %
<p>
<input type="hidden" name="profileType" value="student" />
<input type="submit" value="Créer un compte" />
</p>
</form>
</div>
<div id="employeeForm" class="employee">
<form action="register" method="GET" id="employeeForm">
employeeForm.as_p
% csrf_token %
<p>
<input type="hidden" name="profileType" value="employee" />
<input type="submit" value="Créer un compte" />
</p>
</form>
</div>
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
% endblock %
This is the error for the second button "Créer un compte" (create an account)
This is the template display link 'user_profile.html'
【问题讨论】:
您通过提供太多信息使问题过于复杂。尝试找出问题是表现问题(两种形式都存在,但您没有显示或隐藏正确的形式),是您向客户提供哪些形式的问题,还是您的数据有问题'从客户端接收。 【参考方案1】:您的 jQuery onchange 函数设置为在 column_select
元素上触发;但是,您没有具有该 ID 的元素。大概你的意思是#profilType
。
【讨论】:
以上是关于如何使用正确的字段隐藏/显示我想要的表单的主要内容,如果未能解决你的问题,请参考以下文章