如何使用正确的字段隐藏/显示我想要的表单

时间:2016-01-08 13:28:52

标签: jquery python html django forms

  • 嗨!我需要帮助,我想知道如何隐藏或显示表单。我有2个表单,一个studentForm和EmployeeForm从下拉列表中选择profileType我希望她显示与所选profileType对应的表单

  • 我不知道这是我的jQuery不起作用还是为员工表单创建一个帐户不起作用。我不明白为什么它不起作用。我从数据库中获取表单字段的信息。**

  • 我不知道为什么我第二次出现这个错误,因为第一个按钮运行良好并将信息保存在我的数据库的正确字段中

  • 为了完成我有一个错误,因为在我的模板显示中,两个表单同时出现,只有第一个boutton(Créerunco​​mpte)创建一个帐户工作,而第二个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
  

这是我的views.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 个答案:

答案 0 :(得分:0)

您的jQuery onchange函数设置为在column_select元素上触发;但是,您没有带有该ID的元素。大概你的意思是#profilType