django中ModelForm save方法 以及快速生成空表单或包含数据的表单 包含错误信息

 

django中ModelForm学习系列一~save方法

 

Model代码

 

from django.db import models
# Create your models here.

class ProjectInformation(models.Model):
    """
    项目基本信息
    """

    ResearchClassify = (
        ('药物类','药物类'),
        ('器械类','器械类'),
        ('试剂类', '试剂类'),
        ('临床研究学', '临床研究学'),
        ('纵向课题', '纵向课题'),
        ('废止合同', '废止合同'),
        ('结题项目', '结题项目'),
    )

    protype = models.CharField(max_length=30,verbose_name='项目类型')
    proname = models.CharField(max_length=50,verbose_name='项目名称(中文)')
    proenname = models.CharField(max_length=50,verbose_name='项目名称(英文)')
    studytype = models.CharField(max_length=30, verbose_name='研究分类', choices=ResearchClassify)
    clinicalnum = models.CharField(max_length=30, verbose_name='临床试验备案号')
    leaderunit = models.CharField(max_length=5, choices=(('', ''), ('', '')),verbose_name='本院是否为组长单位')

    class Meta:
        verbose_name = '项目名称(中文)'
        verbose_name_plural = verbose_name


    def __str__(self):
        return self.proname

 

Form代码

 

from django import forms
from django.forms import ModelForm
from .models import ProjectInformation


class ProjectInformationForm(ModelForm):
    class Meta:
        model = ProjectInformation
        localized_fields = ('__all__')

        exclude = ['add_time','filetype',]

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }

 

 

 

 

View代码

def MyProjectSave(request):
    """
    保存表单信息
    """

    form = ProjectInformationForm(request.POST)

    if request.method == 'POST':

        if form.is_valid():

            all_data = form.clean()
            form.save()
        else:
            error = form.errors  #错误信息
            return render(request, 'forms.html', {'form': form, 'error': error})

    return render(request, 'forms.html', {'form': form})
    # return HttpResponseRedirect('/myprojectsave/')

 

 

HTML 代码

<form id = '' name='' action="{% url 'myprojectsave' %}" method="post" autocomplete="off">
    <div class="modal-body">
        {% for field in form %}
                {{ field.errors }}
            <div id = form_row class="row">

                 <div class="form-group">
                    <div class="col-lg-2 form_span chart-container">
                    <span>{{ field.label_tag }}</span>
                    </div>
                    <div class="col-lg-10 form_span chart-container">
                    {{ field }}
                     </div>
                 </div>
            </div>
        {% endfor %}
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭
        </button>
        <button type="submit" id = "jsLoginBtn" class="btn btn-primary">
            提交更改
        </button>
    </div>
    {% csrf_token %}
</form>

 

 

根据model form生成空表单或包含数据的表单

 

 

Model代码

 

 

class CeShi(models.Model):
    realname = models.CharField(max_length=10,verbose_name='姓名',default='')
    nickname = models.EmailField(max_length=10, verbose_name='昵称', default='')

 

 

 

 

Form代码

 

class IndexForm(ModelForm):
    class Meta:
        model = Ceshi
        localized_fields = ('__all__')

        # exclude = ['active', 'is_staff', 'first_name', 'is_active', 'date_joined', 'password', 'username', 'email',
        #            'is_staff', 'last_login', 'password', 'last_name', 'date_joined', 'is_superuser']

        fields = ['realname','company','company_type','project_role','company_person',
                  'registration_number','department','title','education','gender','gcp',
                  'contact_person','mobile','address','introduction']

        widgets = {}


#可以自定义widgets属性包括id,class
       #widgets = {
# 'username': forms.TextInput(
# attrs={
# 'class': 'form-control',
# 'placeholder': '用户名',
# 'id': 'user_name',
# 'required': '请填入用户名',
# }),

# 'password': forms.TextInput(
# attrs={
# 'class': 'form-control',
# 'placeholder':'密码',
# 'id':'pass_word',
# 'required':'请填入密码',
# 'type':'password',
# })
#}

 

View代码

 

    form = IndexForm(auto_id = False)  #生成空表单


    # user = get_object_or_404(CeShi, username=username)
    # form = IndexForm(instance=user)
    #CeShi代表数据库,username代表字段建议用id,IndexForm代表form字段
print(form)

    return render(request, 'index.html', {'form':form})

 

HTML代码

 

<form action="{% url 'usermessage' username %}" method="post" autocomplete="off">
{% for field in form %}

{{ field.errors }}
<div class="row"> <div class="form-group"> <div class="col-lg-2 form_span chart-container"> <span>{{ field.label_tag }}</span></div> <div class="col-lg-10 form_span chart-container">{{ field }}</div></div> </div>
{% endfor %} <input class="btn btn-green" id="jsLoginBtn" type="submit" value="提交 > " />

{% csrf_token %}

</form>

 

自动保存用户名

 

自动保存时间:

created_date = models.DateField(auto_now=True,null=True, blank=True,verbose_name='创建日期')

 

posted on 2017-04-10 14:48  星河赵  阅读(1331)  评论(0编辑  收藏  举报

导航