Django學習筆記

環境:

技術點:

  • format格式化
>>>"{} {}".format("hello", "world")    # 不設置指定位置,按默認順序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 設置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 設置指定位置
'world hello world'
  • http數據傳給前端
from django.http import HttpResponseRedirect, JsonResponse

return JsonResponse({})
  • FORM 字段單獨驗證
class RegisterPostForm(forms.Form):
    mobile = forms.CharField(required=True, min_length=11, max_length=11)
    code = forms.CharField(required=True, min_length=4, max_length=4)
    password = forms.CharField(required=True)

    # 驗證手機號是否已註冊
    def clean_mobile(self):
        mobile = self.data.get("mobile")
        user = UserProfile.objects.filter(mobile=mobile)
        if user:
            raise forms.ValidationError("該手機號已被註冊")
        return mobile
  • 防止basemodel字段生成表
class BaseModel(models.Model):
    add_time = models.DateTimeField(default=datetime.now, verbose_name="添加時間")

    class Meta:
        # 防止BaseModel生成表
        abstract = True
  • django內置用戶密碼加密方法
user = UserProfile(mobile=mobile)
user.set_passdjangoword(password)  # set_password生成加密後的密碼
  • HttpResponseRedirect頁面重定向跳轉
if user is not None:
    # 查詢到用戶
    login(request, user)
    # HttpResponseRedirect頁面重定向
    return HttpResponseRedirect(reverse("index"))
  • model外鍵定義
class Lesson(BaseModel):
    # on_delete表示對應的外鍵數據被刪除後,當前的數據應該怎麼辦
    # 值爲models.SET_NULL不級聯刪除,還需參數null=True, blank=True。值爲models.CASCADE會級聯刪除
    # course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True, blank=True)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    name = models.CharField(verbose_name="章節名", max_length=100)
    learn_times = models.IntegerField(verbose_name="學習時長(分鐘數)", default=0)

    class Meta:
        verbose_name = "課程章節"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
  • 分頁
class CourseListView(View):
    def get(self, request, *args, **kwargs):
        # 獲取課程列表
        all_courses = Course.objects.all().order_by("-add_time")

        # 對課程數據進行分頁
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(all_courses, per_page=5, request=request)

        courses = p.page(page)

        return render(request, "course-list.html", {
            "all_courses": courses
        })


# 注意 all_courses.object_list
{% for course in all_courses.object_list %}
{% endfor %}

<div class="pageturn">
    <ul class="pagelist">

        {% if all_courses.has_previous %}
            <li class="long"><a href="?{{ all_courses.previous_page_number.querystring }}">上一頁</a>
            </li>
        {% endif %}
        {% for page in all_courses.pages %}
            {% if page %}
                {% ifequal page all_courses.number %}
                    <li class="active"><a href="?{{ page.querystring }}">{{ page }}</a></li>
                {% else %}
                    <li><a href="?{{ page.querystring }}" class="page">{{ page }}</a></li>
                {% endifequal %}
            {% else %}
                <li class="none">...</li>
            {% endif %}
        {% endfor %}
        {% if all_courses.has_next %}
            <li class="long"><a
                    href="?{{ all_courses.next_page_number.querystring }}">下一頁</a></li>
        {% endif %}
    </ul>
</div>
  • 取外鍵屬性值
<!--外鍵查找屬性 查找課程外鍵課程機構的名稱-->
<a href="course-detail.html">
    <span class="fl">來自{{ course.course_org.name }}</span>
</a>
  • model數據查詢倒序
# order_by 倒序字段前加「-」
all_courses = Course.objects.all().order_by("-add_time")
  • template對model charfiled choices取值
# model
class Course(BaseModel):
    degree = models.CharField(verbose_name="難度", choices=(("cj", "初級"), ("zj", "中級"), ("gj", "高級")), max_length=2)

# html
難度:<i class="key">{{ course.get_degree_display }}</i>
  • template media_url拼接
<img src="{{ course.image.url }}"/>
# 等同於
<img src="{{ MEDIA_URL }}{{ course.image }}"/>
  • url中設置參數字段獲取
urlpatterns = [
    url(r'(?P<course_id>\d+)/detail/$', CourseDetailView.as_view(), name='detail'),
]

class CourseDetailView(View):
    def get(self, request, course_id, *args, **kwargs):
        pass
  • 字典循環取數據快捷寫法
user_courses = UserCourse.objects.filter(course=course)
user_ids = [user_course.user.id for user_course in user_courses]
  • template for循環取索引下標
{% for teacher in hot_teachers %}
# forloop.counter0 會獲得從0開始計算的下標
# forloop.counter 會獲得從1開始計算的下標
<span class="num fl">{{ forloop.counter }}</span>
{% endfor %}
  • template過濾處理
<input type="text" value="{{ user.birthday|default_if_none:''|date:'Y-m-d' }}"/>
相關文章
相關標籤/搜索