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 参数初始化

  • 相关阅读:
    Max Sum Plus Plus HDU
    Monkey and Banana HDU
    Ignatius and the Princess IV HDU
    Extended Traffic LightOJ
    Tram POJ
    Common Subsequence HDU
    最大连续子序列 HDU
    Max Sum HDU
    畅通工程再续
    River Hopscotch POJ
  • 原文地址:https://www.cnblogs.com/klvchen/p/11244432.html
Copyright © 2011-2022 走看看