开启代码之旅 Launch With Code


1410 浏览 5 years, 11 months

7 Using Django Forms

版权声明: 转载请注明出处 http://www.codingsoho.com/

form的修改包括

  • 创建新的form文件,并定义form
  • View中对form进行处理,包括, Get,Post
  • 模板中添加form

新建form文件lwc/forms.py,并定义form

from django import forms
from .models import Join

class EmailForm(forms.Form):
    name = forms.CharField(required = False)
    email = forms.EmailField()

class JoinForm(forms.ModelForm):
    class Meta:
        model = Join

添加对form的处理

  • nonModel Form
  • ModelForm

joins/views.py

def home(request):
    form = EmailForm(request.POST or None)
    if form.is_valid():
        email =  form.cleaned_data['email']
        new_join, created = Joins.objects.get_or_create(email=email)
        print new_join, created
    form = JoinForm(request.POST or None)
    if form.is_valid():
        new_join = form.save(commit = False)
        email = form.cleaned_data['email']
        new_join_old, created = Join.objects.get_or_create(email = email)
    context = {"form":form}
    template = "home.html"
    return render(request, template, context)

模板中添加form

templates/home.html

{% extends "base.html" %}

{% block content %}
<h1> Welcome Home! </h1>

<form method="POST" action=""> {% csrf_token %}
    <input type="email" name="email" placeholder="Your email..." />
    {{form.as_p}}
    <input type="submit" value="join" class="btn" />
</form>
{% endblock %}

method 这儿可以是GET或者POST
action 是url
{% csrf_token %} 安全,防止密码泄露
form可以用non-Model form或者model form