zoukankan      html  css  js  c++  java
  • Django Form 初始化数据

    修改 urls.py 添加

        path('initial.html', views.initial),
    

    修改 models.py

    class UserInfo(models.Model):
        name = models.CharField(max_length=32)
        ut = models.ForeignKey('UserType', on_delete=models.CASCADE)
    

    创建数据库

    python manage.py makemigrations
    python manage.py migrate
    

    插入表数据

    修改 views.py

    def initial(request):
        from app01 import models
        if request.method == 'GET':
            nid = request.GET.get('nid')
            m = models.UserInfo.objects.filter(id=nid).first()
            dic = {'username': m.name, 'user_type': m.ut_id}
    
            obj = forms.InitialForm(dic)
            return render(request, 'initial.html', {'obj': obj})
    
    

    修改 forms.py

    class InitialForm(DForms.Form):
        username = fields.CharField()
        user_type = fields.IntegerField(
            widget=widgets.Select(choices=[])
        )
    
        def __init__(self, *args, **kwargs):
            # 执行父类构造方法
            super(InitialForm, self).__init__(*args, **kwargs)
    
            self.fields['user_type'].widget.choices = models.UserType.objects.all().values_list('id', 'caption')
    

    在 templates 文件夹下创建 initial.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        {{ obj.username }}
        {{ obj.user_type }}
    </body>
    </html>
    

    访问 http://127.0.0.1:8000/initial.html?nid=2 ,根据 nid=2 参数初始化

  • 相关阅读:
    Linux下制作和使用静态库和动态库
    C语言的内存管理
    C语言柔性数组
    大小端模式
    C位域操作
    C/C++字节对齐
    C/C++指针
    Linux之Socket编程
    VSCode配置FTP
    GCC的编译过程和链接
  • 原文地址:https://www.cnblogs.com/klvchen/p/11244432.html
Copyright © 2011-2022 走看看