使用django框架(modelform模块)实现增删改查的完整过程(考虑数据重复问题)

1、创建url

    path('num/list/',views.num_list),
    path('num/model/form/add/',views.num_model_form_add),
    path('num/<int:nid>/edit/',views.num_edit),
    path('num/<int:nid>/delete/', views.num_delete),

2、创建表结构

class PrettyNum(models.Model):
    "靓号表"
    mobile=models.CharField(verbose_name="手机号",max_length=11)
    # 允许为空 null=True,blank= True
    price=models.IntegerField(verbose_name="价格",default=0)
    level_choices=(
        (1, '1级'),
        (2, '2级'),
        (3, '3级'),
        (4, '4级'),
    )
    level=models.SmallIntegerField(verbose_name="级别",choices=level_choices,default=1)

    staus_choices=(
        (1,"已占用"),
        (2,"未使用")
    )
    status=models.SmallIntegerField(verbose_name="状态",choices=staus_choices,default=2)

3、编写函数

# 靓号管理
def num_list(request):
    # prettynum = models.PrettyNum.objects.all()
    # 按照level排序,不加负号为从小到大,加上为从大到小
    prettynum = models.PrettyNum.objects.all().order_by("-level")
    return render(request, "num_list.html", {"prettynum": prettynum})



from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class PrettyModelForm(forms.ModelForm):
    # 号码不可以被修改
    # mobile=forms.CharField(disabled=True,label="手机号")
    # 验证方法一 对号码格式进行限制
    # mobile=forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格试错误'),],
    # )

    class Meta:
        model=models.PrettyNum
        fields=["mobile",'price','level','status']


    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={"class":"form-control","placeholder":field.label}

    # 验证方法二
    def clean_mobile(self):
        txt_mobile=self.cleaned_data["mobile"]
        # 存在TRUE不存在False
        exists=models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("该手机号已经存在")
        if len(txt_mobile) != 11:
            raise ValidationError("格式错误")

        return txt_mobile


def num_model_form_add(request):
    if request.method=="GET":
        form=PrettyModelForm()
        return  render(request,"num_model_form_add.html",{"form":form})
    form=PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/num/list/")
    return render(request,"num_model_form_add.html",{"form":form})

class PrettyEditModelForm(forms.ModelForm):
    # 不能修改手机号
    # mobile=forms.CharField(disabled=True,label="手机号")
    class Meta:
        model=models.PrettyNum
        fields=['mobile','price','level','status']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs={"class":"form-control","placeholder":field.label}

    # 验证方法二
    def clean_mobile(self):
        txt_mobile=self.cleaned_data["mobile"]
        # 存在TRUE不存在False
        # 去掉本个记录,查找是否有其他手机号相同的记录
        exists=models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("该手机号已经存在")
        if len(txt_mobile) != 11:
            raise ValidationError("格式错误")
        return txt_mobile


def num_edit(request,nid):
    row_object=models.PrettyNum.objects.filter(id=nid).first()
    if request.method=="GET":
        form=PrettyEditModelForm(instance=row_object)
        return render(request,"num_edit.html",{"form":form})

    form=PrettyEditModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/num/list/')
    return render(request, "num_edit.html", {"form": form})

def num_delete(request,nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/num/list/")


4、编写html页面(例:list页面)

{% extends 'header.html' %}
{% block css %}

{% endblock %}
{% block content %}
    <div>

        <div class="container">
            <div style="margin-bottom: 10px">
                <a class="btn btn-success" href="/num/model/form/add/" target="_blank">
                    <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                    新建靓号
                </a>
            </div>
            <div class="panel panel-default">
                <div class="panel-body">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    靓号列表
                </div>
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>号码</th>
                        <th>价格</th>
                        <th>级别</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in prettynum %}
                        <tr>
                            <td>{{ obj.id }}</td>
                            <td>{{ obj.mobile }}</td>
                            <td>{{ obj.price }}</td>
                            <td>{{ obj.get_level_display }}</td>
                            <td>{{ obj.get_status_display }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/num/{{ obj.id }}/edit/">编辑</a>
                                <a class="btn btn-danger btn-xs" href="/num/{{ obj.id }}/delete/">删除</a>
                            </td>

                        </tr>
                    {% endfor %}

                    </tbody>
                </table>
            </div>
        </div>
    </div>
{% endblock %}
{% block js %}
{% endblock %}
</body>
</html>

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值