Thursday, 14 March 2019

django 17 ModelForm and CreateView



#music/models

from django.db import models
from django.urls import reverse

class Album(models.Model):
    artist = models.CharField(max_length=50)
    album_title = models.CharField(max_length=50)
    genre = models.CharField(max_length=50)
    album_logo = models.CharField(max_length=500)

    #form with no action redirect to detail
    def get_absolute_url(self):
        return reverse('music:detail', kwargs={'pk': self.pk})

    #query album.objects.get(pk=1)
    def __str__(self):
        return self.album_title + ' - ' + self.artist

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=50)
    song_title = models.CharField(max_length=50)
    is_favorite = models.BooleanField(default=False)

    def __str__(self):
        return self.song_title

-------------------------------------

#music/urls

from django.urls import path
from . import views

app_name = 'music'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),

    #/music/id/
    path('<pk>/', views.DetailView.as_view(), name='detail'),

    #music/album/add/
    path('album/add/', views.AlbumCreate.as_view(), name='album-add')
]

---------------------------------------
#music/views

from django.views import generic
from .models import Album
from django.views.generic.edit import  CreateView, UpdateView, DeleteView

class IndexView(generic.ListView):
    template_name = 'music/index.html'

    def get_queryset(self):
        return  Album.objects.all()

class DetailView(generic.DeleteView):
    model = Album
    template_name = 'music/detail.html'

class AlbumCreate(CreateView):
    model = Album
    fields = ['artist', 'album_title', 'genre', 'album_logo']

---------------------------------------------
#music/templates/music/album_form

{% extends 'music/base.html' %}
{% block title %}New Album{% endblock %}
{% block albums_active %}active{% endblock %}

{% block body %}
    <div class="container-fluid">

        <div class="row">

            <div class="col-sm-12 col-md-7">

                <div class="panel panel-default">

                    <div class="panel-body">

                        <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                            {% csrf_token %}
                            {% include 'music/form-template.html' %}
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-success" >Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

------------------------------------
#music/templates/form-template

{% for field in form %}

    <div class="form-group">

        <div class="col-sm-offset-2 col-sm-10">

            <span class="text-danger small">{{ field.errors }}</span>
        </div>
        <label class="control-label col-sm-2">{{ field.label_tag }}</label>
        <div class="col-sm-10">{{ field }}</div>
    </div>
{% endfor %}

reference:
https://stackoverflow.com/questions/43139081/importerror-no-module-named-django-core-urlresolvers

你支持极简的生活吗?

以前看到过一则故事,讲的是一户人家打算做一个家庭大扫除,他们从车库开始清理,但是很快他们发现,东西太多,而且堆叠的杂乱无章,零碎又琐碎。

整理耗费的时间比预期长了很多,正烦恼的时候,邻居一句:“你拥有得越多,被占有得也就越多。”

让他醍醐灌顶,打算改变自己的生活方式。

其实很多人都有这样的困恼,但很多时候,这些困恼却偏偏是拥有太多造成的,其实有时候,拥有的越多并不等同幸福。

清除掉那些99%对自己无用的东西,然后集中精力过好剩下的1%,你会获得更轻松自在的人生。


01

越简单,越美好。

当今社会是一个欲望膨胀、同时又消费至上的时代,很多人都觉得,自己拥有得越多,消费得越多,生活就是美好的。

但其实想一想,你拥有的太多,被占有的也会更多,举个简单的例子,女生都喜欢买衣服,每到换季恨不得把整个衣柜都翻新一遍。

然而不管买多少新衣服,真正经常穿的,无外乎就那几件,反倒是家里的空间慢慢被你买的东西填满。

生活的压力原本已经很大了,加上不断膨胀的欲望,就变成了压在人们肩头上的负担,让人喘不过气,逼的人迷失自己。

所以,丢掉那些没用的东西,丢掉那些负担以及多余的想法,追求极简的生活,不仅会让你更自由,使你在精神层面得以扩展,而不是依靠物质的积累。


02

如何做到极简。

关于极简生活,我有几点建议:

1. 物质上只拥有必需之物

意大利经济学家巴莱多提出一个定律,叫做“二八法则”,他认为,在任何一组东西中。

最重要的只占其中一小部分,约20%,其余80%尽管是多数,却是次要的。

换句话说,我们拥有太多的选择、过多的欲望,就容易把时间放在不重要的事情上,而少去关注真正重要的事情。

2. 时间上少浪费就是多拥有

时间就是生命,它也是我们最能够控制的因素,昨天不管如何,都已成为了过去,我们要做的,应该是认真的对待今天,专注于当下,才是对时间的最好回馈。

生活简单了,我们也就拥有更有的时间和精力,不在没必要的事情上浪费时间,少浪费就是在多拥有!

3. 工作上做的越少,效率越高

有的人每天看似忙得脱不开身,手头上好几件工作,但是最后反而都没做好。

而有的人只关注与一件事,认认真真,完成了再接着做下一件事,反而有条不紊效率高。

工作不仅要看数量,更重要的是质量,所以要改变自己利用时间的质量,锻炼自己的注意力和排除杂念的能力。

把精力放在重要的事情上面,一心一用远比一手抓效率高得多。

Wednesday, 13 March 2019

django 16 generic views



#music/urls

from django.urls import path
from . import views

app_name = 'music'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),

    #/music/id/
    path('<pk>/', views.DetailView.as_view(), name='detail'),

]
-------------------------------------
#music/views

from django.views import generic
from .models import Album

class IndexView(generic.ListView):
    template_name = 'music/index.html'

    def get_queryset(self):
        return  Album.objects.all()

class DetailView(generic.DeleteView):
    model = Album
    template_name = 'music/detail.html'

---------------------------------------
#music/templates/music/index

{% extends 'music/base.html' %}
{% block title %}Albums{% endblock %}

{% block body %}

    <ul>
        {% for album in object_list %}
            <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li>
        {% endfor %}
    </ul>

{% endblock %}

--------------------------------------
#music/templates/music/detail

{% extends 'music/base.html' %}
{% block title %}Songs{% endblock %}

{% block body %}
    <img style="height: 150px;" src="{{album.album_logo}}">
    <h1>{{album.album_title}}</h1>
    <h3>{{album.artist}}</h3>

    {% for song in album.song_set.all %}
        {{ song.song_title }}

        {% if song.is_favorite %}
            <img src="http://i.imgur.com/b9b13Rd.png"><br>
        {% endif %}
        <br>
    {% endfor %}

{% endblock %}

Monday, 11 March 2019

django 15 base html




#music/templates/music/base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% load staticfiles %}
    <!-- my css -->
    <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}"/>
    <!-- bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <!-- google fonts -->
    <link href="https://fonts.googleapis.com/css?family=Srisakdi" rel="stylesheet">
    <title>{% block title %}Django{% endblock %}</title>
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

    <nav class="navbar navbar-expand-lg navbar-light" style="background-color: #fcefe5;">
        <a class="navbar-brand" style="font-family: 'Srisakdi', serif; font-weight: bold; text-shadow: 4px 4px 4px #aaa;" href="{% url 'music:index' %}">Django</a>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
         <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarTogglerDemo02">
          <ul class="navbar-nav">
            <li class="nav-item active">
              <a class="nav-link" href="{% url 'music:index' %}"><span class="glyphicon glyphicon-cd" aria-hidden="true"></span>&nbsp Albums</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#"><span class="glyphicon glyphicon-music" aria-hidden="true"></span>&nbsp Songs</a>
            </li>
          </ul>

            <form class="navbar-form navbar-left" role="search" method="get" action="#">
                <div class="form-group">
                    <input type="text" name="q" value=""/>
                </div>
                <button type="submit" >Search</button>
            </form>

            <ul class="navbar-nav navbar-right">
                <li>
                    <a class="nav-link" href="#">
                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Add Album
                    </a>
                </li>
                <li>
                    <a class="nav-link" href="#">
                        <span class="glyphicon glyphicon-off" aria-hidden="true"></span>&nbsp; Logout
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    {% block body %}
    {% endblock %}
</body>
</html>

------------------------------------------------
#music/templates/music/index.html

{% extends 'music/base.html' %}
#overwrite title
{% block title %}Albums{% endblock %}

{% block body %}
    {% if all_albums %}
    <ul>
        {% for album in all_albums %}
        <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li>
        {% endfor %}
    </ul>
    {% else %}
    <h3>There is no album</h3>
    {% endif %}
{% endblock %}

------------------------------------------------
#music/templates/music/detail.html

{% extends 'music/base.html' %}
{% block title %}Songs{% endblock %}

{% block body %}
    <img style="height: 150px;" src="{{album.album_logo}}">
    <h1>{{album.album_title}}</h1>
    <h3>{{album.artist}}</h3>

    <form action="{% url 'music:favorite' album.id %}" method="post">
        {% csrf_token %}
        {% for song in album.song_set.all %}
            <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}" />
            <label for="song{{ forloop.counter}}">
                {{ song.song_title }}
                {% if song.is_favorite %}
                    <img src="https://img.icons8.com/material/24/000000/star.png"><br>
                {% endif %}
            </label><br>
        {% endfor %}
        <input type="submit" value="Favorite">
    </form>
{% endblock %}

Sunday, 10 March 2019

django 14 css bootstrap




#music/templates/music/index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% load staticfiles %}
    <!-- my css -->
    <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}"/>
    <!-- bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
     <!-- google fonts -->
    <link href="https://fonts.googleapis.com/css?family=Srisakdi" rel="stylesheet">
    <title>Albums</title>
</head>
<body>
  <!-- bootstrap -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

    <nav class="navbar navbar-expand-sm navbar-light" style="background-color: #fcefe5;">
        <a class="navbar-brand" style="font-family: 'Srisakdi', serif; font-weight: bold; text-shadow: 4px 4px 4px #aaa;" href="{% url 'music:index' %}">Django</a>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
         <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarTogglerDemo02">
          <ul class="navbar-nav">
            <li class="nav-item active">
              <a class="nav-link" href="{% url 'music:index' %}"><span class="glyphicon glyphicon-cd" aria-hidden="true"></span>&nbsp Albums</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#"><span class="glyphicon glyphicon-music" aria-hidden="true"></span>&nbsp Songs</a>
            </li>
          </ul>
        </div>
    </nav>

    {% if all_albums %}
        <ul>
            {% for album in all_albums %}
                <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <h3>There is no album</h3>
    {% endif %}
</body>
</html>

-----------------------------------
#music/static/music/style.css

body{
    height: 100vh;
    background: white url("images/background.jpg");
    background-repeat: no-repeat;
    background-size: 100% 100%;
}

Friday, 8 March 2019

django 13 form

#music/urls

from django.urls import path
from . import views

app_name = 'music'

urlpatterns = [
    path('', views.index, name='index'),

    #/music/id/
    path('<album_id>/', views.detail, name='detail'),

    #/music/id/favorite/
    path('<album_id>/favorite/', views.favorite, name='favorite'),
]

-----------------------------------------------
#music/views

from .models import Album, Song
from django.shortcuts import render, get_object_or_404

def index(request):
    all_albums = Album.objects.all()
    return render(request, 'music/index.html', {'all_albums': all_albums,})

def detail(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    return render(request, 'music/detail.html', {'album': album})

def favorite(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    try:
        selected_song = album.song_set.get(pk=request.POST['song'])
    except (KeyError, Song.DoesNotExist):
        return render(request, 'music/detail.html', {
            'album': album,
            'error_message': 'You did not select a valid song',
        })
    else:
         if selected_song.is_favorite:
            selected_song.is_favorite = False
        else:
            selected_song.is_favorite = True
        selected_song.save()
        return render(request, 'music/detail.html', {'album': album})

-----------------------------------
#music/templates/music/detail

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Detail</title>
</head>
<body>
    <img src="{{album.album_logo}}">
    <h1>{{album.album_title}}</h1>
    <h3>{{album.artist}}</h3>

    {% if error_message %}
        <p><strong>{{error_message}}</strong></p>
    {% endif %}

    <form action="{% url 'music:favorite' album.id %}" method="post">
        {% csrf_token %}
        {% for song in album.song_set.all %}
            <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}" />
            <label for="song{{ forloop.counter}}">
                {{ song.song_title }}
                {% if song.is_favorite %}
                    <img src="https://img.icons8.com/material/24/000000/star.png"><br>
                {% endif %}
            </label><br>
        {% endfor %}
        <input type="submit" value="Favorite">
    </form>
</body>
</html>