美文网首页python之路
django笔记(五)form表单组件

django笔记(五)form表单组件

作者: 非鱼2018 | 来源:发表于2021-02-10 11:24 被阅读0次

    今年回不了家了,看不到农村老家CBD的繁华了,去年在家呆了一个月
    今年算是还回去了,出来混迟早都是要还的,只是想不到回来的这么快,哈哈
    在深圳第三次过年,本来计划春节前写完15篇django笔记,现在看来是完不成了,
    提前祝大家新年快乐
    希望明年疫情早点结束,口罩真是带的够够的了。。。

    1.基于模型的form

    models.py
    
    sex_choice = (
    
        ('男', 'Male'),
    
        ('女', 'Famale'),
    
    )
    
    # form表单测试 20200109
    
    class Userinfo(models.Model):
    
        name=models.CharField(max_length=100)
    
        age=models.IntegerField(blank=True,null=True)
    
        sex = models.CharField(max_length=3, choices=sex_choice)  #默认为male
    
        def __str__(self):
    
            """Return a string representation of the model."""
    
            return self.name
    

    forms.py

    from django import forms
    
    from .models import Userinfo,sex_choice
    
    class UserinfoForm(forms.ModelForm):
    
        class Meta:
    
            model = Userinfo
    
            fields='__all__'
    
            #fields=['name','sex']
    
            #exclude=('age',)
    
            help_texts = {
    
                'name': '请输入姓名',
    
                'sex':'请选择性别',
    
                'age':'请输入年龄'
    
            }
    
            # 在页面上显示的label名称,加*表示必填,因为age可以为空
    
            labels = {"name": "*姓名","age":"年龄","sex":"*性别"}
    
            # widgets = {
    
            #     'name': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
    
            # }
    

    views.py

    from .forms import UserinfoForm
    
    def userinfo(request):
    
        if request.method == 'GET':
    
            form = UserinfoForm()
    
        else:
    
            form = UserinfoForm(data=request.POST)
    
            if form.is_valid():
    
                new_user=form.save(commit=False)  #commit=false表示暂时不提交
    
                new_user.age=100  #设置其他字段的值,然后保存
    
                new_user.save()
    
                return HttpResponse('<h3>新增用户信息成功</h3>')
    
                #return redirect("myapp:titles")
    
        content = {'form': form}
    
        return render(request, 'myapp/userinfo.html', content)
    

    userinfo.hrml

    <h1>新增用户</h1>
    
      <form action="{% url 'myapp:userinfo'%}"  method="post">
    
            {% csrf_token %}
    
          {{ form.as_p }}
    
    <input type="submit" value="提交">
    
        </form>
    

    url.py

        path('userinfo/',views.userinfo,name='userinfo'),
    
        path('userinfo2/',views.userinfo2,name='userinfo2'),
    
        path('userinfo3/',views.userinfo2,name='userinfo3'),
    

    2.自定义form

    forms.py

    # 自定义forms2
    
    from .models import sex_choice
    
    class UserinfoFrom2(forms.Form):
    
        name = forms.CharField(max_length=100)
    
        age = forms.IntegerField(required=False,max_value=100,min_value=1)
    
        sex = forms.CharField(max_length=3,
    
                              widget=forms.Select(choices=sex_choice))  # 默认为male
    
      views.py
    
    #2.表单测试2
    
    from .forms import UserinfoFrom2
    
    from .models import Userinfo
    
    def userinfo2(request):
    
        if request.method == 'GET':
    
            form = UserinfoFrom2()
    
        else:
    
            form = UserinfoFrom2(data=request.POST)
    
            if form.is_valid():
    
                data=form.cleaned_data
    
                Userinfo.objects.create(**data)
    
                return HttpResponse('<h3>新增用户信息成功</h3>')
    
        content = {'form': form}
    
        return render(request, 'myapp/userinfo2.html', content)
    

    userinfo2.html

    h1>新增用户</h1>
    
      <form action="{% url 'myapp:userinfo2'%}"  method="post">
    
            {% csrf_token %}
    
          {{ form.as_p }}
    
    <input type="submit" value="提交">
    
        </form>
    

    3.不使用form组件,直接写表单

    userinfo3.html

    <h1>新增用户</h1>
    
      <form action="{% url 'myapp:userinfo3'%}"  method="post">
    
            {% csrf_token %}
    
         <p>姓名:<input type="text" name="name"></p>
    
        <p>年龄:<input type="text" name="age"></p>
    
        <p>性别:<select name='age'>
    
       <option value ="男">male</option>
    
    <option value ="女">famle</option>
    
        </select>
    
    <input type="submit" value="提交">
    
        </form>
    

    userinfo3.html

    from .forms import UserinfoFrom2
    
    from .models import Userinfo
    
    def userinfo3(request):
    
        if request.method == 'GET':
    
            return render(request, 'myapp/userinfo3.html')
    
        else:
    
            # name=request.POST['name']
    
            # age=request.POST['age']
    
            # sex = request.POST['sex']
    
            Userinfo.objects.create(**request.POST)
    
            return HttpResponse('<h3>新增用户信息成功</h3>')
    
    image.png

    相关文章

      网友评论

        本文标题:django笔记(五)form表单组件

        本文链接:https://www.haomeiwen.com/subject/iscuzktx.html