Dajngo学习笔记(3)

电话号码管理

查看功能

class PrettyNum(models.Model):
    mobile=models.CharField(verbose_name="电话号",max_length=11)
    price=models.IntegerField(verbose_name="价格")
    level_choice=(
        (1,"一级"),
        (2,"二级"),
        (3,"三级")
    )
    level=models.SmallIntegerField(verbose_name="级别",choices=level_choice,default=1)
    status_choice=(
        (1,"未占用"),
        (2,"占用")
    )
    status=models.SmallIntegerField(verbose_name="状态",choices=status_choice,default=1)
makemigrations

migrate
def num_list(request):
    queryset=models.PrettyNum.objects.all().order_by("-level")#-表示递减  无表示递增
    for obj in queryset:
        print(obj.id,obj.mobile,obj.price,obj.get_level_display(),obj.get_status_display())
    return render(request,"num_list.html",{"queryset":queryset})
{% extends "layout.html" %}

{% block content %}

<div>
    <div class="container">
        <div style = "margin-bottom: 10px">
            <a class="btn btn-primary" href="/num/add" >
{#              target="_blank"  在新的页面产生#}
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true">span>
                新建电话号
            a>
        div>
        <div class="panel panel-default">
      
      <div class="panel-heading"><span class="glyphicon glyphicon-th-list" aria-hidden="true"> 电话号管理span>div>
      
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>#th>
            <th>IDth>
            <th>电话号th>
              <th>价格th>
              <th>等级th>
              <th>状态th>
            <th>操作th>
          tr>
        thead>
        <tbody>
        {% for obj in queryset %}
        <tr>
            <th scope="row">{{ obj.id }}th>
            <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/delete/?nid={{ obj.id }}">删除a>
            td>
        tr>
        {% endfor %}
        tbody>
      table>
    div>
    div>
div>

{% endblock %}

Dajngo学习笔记(3)_第1张图片

新增功能

其中可以对数据进行验证

class NumModelForm(forms.ModelForm):
    # mobile=forms.CharField(
    #     label="电话号",
    #     validators=[RegexValidator(r"^1[3-9]\d{9}","电话号格式错误")],
    # )
    class Meta:
        model=models.PrettyNum
        #fields=["mobile","price","level","status"]
        fields="__all__"#选择全部字段
        #exclude=["level"]#排除level字段
    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"]
        exists=models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号存在")
        if len(txt_mobile)!=11:
            #验证不通过
            raise ValidationError("格式错误")
        return txt_mobile
{% extends "layout.html" %}

{% block content %}
<div>
    <div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">新建面板h3>
  div>
  <div class="panel-body" >
      <form method="post" novalidate>
          {% csrf_token %}

      {% for field in form %}
          <div class="form-group">
         <label> {{ field.label }}
          label>
          {{ field  }}
              <span style="color: red">{{ field.errors.0 }}span>

          div>
          {% endfor %}

      <button type="submit" class="btn btn-primary">保存button>
    form>

  div>
div>
div>

{% endblock %}

Dajngo学习笔记(3)_第2张图片
如果不符合要求

Dajngo学习笔记(3)_第3张图片

编辑

class NumEditModelForm(forms.ModelForm):
    mobile=forms.CharField(disabled=True,label="手机号")

    class Meta:
        model=models.PrettyNum
        #fields=["mobile","price","level","status"]
        fields="__all__"#选择全部字段
        #exclude=["mobile"]#排除level字段
    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 num_edit(request,nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        form = NumEditModelForm(instance=row_object)
        return render(request, "num_edit.html", {"form": form})
    form = NumEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/num/list/")
    return render(request, "num_edit.html", {"form": form})
{% extends "layout.html" %}

{% block content %}
<div class="container">
<div>
    <div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">新建面板h3>
  div>
  <div class="panel-body" >
      <form method="post" novalidate>
          {% csrf_token %}

      {% for field in form %}
          <div class="form-group">
         <label> {{ field.label }}
          label>
          {{ field  }}
              <span style="color: red">{{ field.errors.0 }}span>

          div>
          {% endfor %}

      <button type="submit" class="btn btn-primary">保存button>
    form>

  div>
div>
div>

div>
{% endblock %}

编辑时候不允许手机号重复

class NumEditModelForm(forms.ModelForm):
    #mobile=forms.CharField(disabled=True,label="手机号")#不允许编辑手机号

    class Meta:
        model=models.PrettyNum
        #fields=["mobile","price","level","status"]
        fields="__all__"#选择全部字段
        #exclude=["mobile"]#排除level字段
    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"]
        txt_id = self.instance.pk#当前编辑的id
        exists=models.PrettyNum.objects.exclude(id=txt_id).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号存在")
        if len(txt_mobile)!=11:
            #验证不通过
            raise ValidationError("格式错误")
        return txt_mobile

你可能感兴趣的:(web开发,学习,笔记,windows)