django学习——ModelForm

ModelForm

  • ModelForm简单介绍
  • ModelForm的使用

ModelForm简单介绍

ModelForm就是将ModelForm进行绑定,Form有自动生成表单的作用,而Model包含了数据库表所有的数据字段。如果单单使用Form的话,我们需要定义每一个form字段,而将ModelForm组合起来的话,ModelForm就有着以下功能:

  • Form所有的功能
  • Model字段自动转换成form字段

ModelForm的使用

  • 1、在forms.py文件里创建ArticleForm类继承forms.ModelForm
    from django import forms
    from .models import Article
    
    
    class ArticleForm(forms.ModelForm):
        class Meta:
            model = Article
            fields = "__all__"  # 字段,如果是__all__,就是表示列出所有的字段
            exclude = None  # 排除的字段
            # 提示信息
            labels = {
           
                'title': '标题',
                'content': '内容',
                'author': '作者',
            }
            help_texts = None  # 帮助提示信息
    
            # 自定义插件
            widgets = None
            from django.forms import widgets as wid
            # widgets = {
           
            #     'content': wid.Textarea()
            # }
    
            # 自定义错误信息
            error_messages = {
           
                'title': {
           'required': '标题不能为空'},
                'content': {
           'required': '内容不能为空'},
                'author': {
           'required': '作者不能为空'}
            }
    
        def get_errors(self):
            errors = self.errors.get_json_data()
            new_errors = {
           }
            for key, message_dicts in errors.items():
                messages = []
                for message in message_dicts:
                    messages.append(message['message'])
                new_errors[key] = messages
            return new_errors
    
    
  • 2、在models.py文件里创建Article模型
    from django.db import models
    
    
    class Article(models.Model):
        title = models.CharField(max_length=20)
        content = models.TextField()
        author = models.CharField(max_length=10)
        create_time = models.DateTimeField(auto_now=True)
    
        class Meta:
            db_table = 'article'
    
    
  • 3、在views.py文件里定义一个视图类,创建get和post方法
    from django.shortcuts import render
    from django.views import View
    from .forms import ArticleForm
    
    
    class ArticleView(View):
        def get(self, request):
            form = ArticleForm()
            return render(request, 'article.html', {
           'form': form, 'result': ''})
    
        def post(self, request):
            form = ArticleForm(request.POST)
            if form.is_valid():
                title = form.cleaned_data.get('title')
                content = form.cleaned_data.get('content')
                author = form.cleaned_data.get('author')
                print(title, content, author)
                # 保存数据到数据库表里
                form.save()
                # 如果在save()方法里传入commit=False,则会生成这个模型的对象
                # article = form.save(commit=False)
                # article.title = '天龙八部(新)'
                # article.save()
                return render(request, 'article.html', {
           'form': form, 'result': 'submit success'})
            else:
                form = ArticleForm(request.POST)
                print(form.get_errors())
                return render(request, 'article.html', {
           'form': form, 'result': 'submit failed'})
    
    
  • 4、在urls.py文件里映射路由
    from django.urls import path
    from . import views
    
    
    urlpatterns = [
        path('article/', views.ArticleView.as_view(), name='article')
    ]
    
    
  • 5、创建html模板文件
    
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
        <form action="" method="POST">
            <table>
                {
          { form.as_table }}
                <tr>
                    <td>td>
                    <td><input type="submit" value="提交">td>
                tr>
            table>
        form>
        {
          { result }}
    body>
    html>
    

你可能感兴趣的:(python,django,form表单,ModelForm)