Showing posts with label Django. Show all posts
Showing posts with label Django. Show all posts

12/30/2017

Django + install rich html text editor (WYSIWYG, ckeditor)


I recommend you do this on virtual-env.

1. install packages

pip install django-ckeditor
pip install image (optional)

2. Set settings.py

Add ckeditor in INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin',                   
                   'django.contrib.auth',                   
                    ... 
                   'ckeditor',]

Add this contents end of settings.py
CKEDITOR_UPLOAD_PATH = "uploads/" 
CKEDITOR_CONFIGS = { 
    'default': { 'toolbar': None, },
}

3. Set url.py

Add "url(r'^ckeditor/', include('ckeditor_uploader.urls'))," in urlpatterns
urlpatterns = [ url(r'^admin/', admin.site.urls),                
               ... 
                url(r'^ckeditor/', include('ckeditor_uploader.urls')),                
]

4. set models.py

Add import RichTextField
change "models.TextField()" to "RichTextField()"

from ckeditor.fields import RichTextField 
# Create your models here 
class OpenCV_Post(models.Model): 
    author = models.ForeignKey('auth.User') 
    title = models.CharField(max_length=200)
    # text = models.TextField()    
    text = RichTextField()

5. migration!

>>python manage.py makemigrations
>>python manage.py migrate


The Result on Admin






reference
https://www.youtube.com/watch?v=W8PTD7SszDI

12/24/2017

django + mysql setting (Mac or Linux)

A. mysql install

1. download mysql

https://dev.mysql.com/downloads/mysql/



* site may ask to join, but we don't need to join for download file
* install -> in case of Mac, show default password on popup window.

2. set path

$nano ~/.bash_profile 
add this sentence 

#mysql
export PATH=/usr/local/mysql/bin:$PATH

3. start mysql & set password

$ sudo /usr/local/mysql/support-files/mysql.server start

create a username with a password
$ mysqladmin -u root password yourpassword
or
change the password
$ mysqladmin -u root -p'oldpassword' password newpassword

4. create mysql database

login
$ mysql -u root -p
Enter password:

create database
CREATE DATABASE taskbuster_db;



B. django setting

1. install pymysql

$pip install pymysql

2. django settings.py

import pymysql
pymysql.install_as_MySQLdb()

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',        
'NAME': 'django_locker', # DB name        
'USER': '', # database user : root        
'PASSWORD': '', # database pass         
'HOST': '', # localhost        
'PORT': '', # database port('' or 3306)    }
}


3. migration

$python manage.py makemigrations

$python manage.py migrate



12/10/2017

Django queryset simple tutorial


I have 4 objects in my table. The table name is 'Post'.



In models.py, the db class is like that:
class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title


So, let's train how to access the db and handle this.
Above all, you have to makemigrations, migrate after adding the db class code.

>python manage.py makemigrations
>python manage.py migrate


----
OK, train to the QuerySet (we call the dango query as QuerySet),
input this command in the console.
>python manage.py shell


OK, so now let's see the some commands
I will introduce very simple and useful commands.


1. show all objects

>from webapp.models import Post
: db import
>Post.objects.all()




2. access specific object

- first object
>Post.objects.all().first()
- last object
>Post.objects.all().last()
- 3rd object
>Post.objects.all()[2]




very easy right? 😴


3. element value change in object and save

> obj = Post.objects.all()[2]
>obj.title = 'a_title_3'
>obj.save()






4. object add and save

>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()


5. Checking for empty queryset in Django

if table_name.objects.all().count() == 0:
     print('none')


6. auto increase primary field

id = models.AutoField(primary_key=True)


7. Query datetime by today, yesterday's date 

visitor table class is like that:
class visitor_ss2r(models.Model):
    id = models.AutoField(primary_key=True)
    count = models.PositiveIntegerField(default=0)
    day_visiting = models.DateField(auto_now=True)

today search
(notice!) import datetime 
visitor.objects.get(day_visiting=datetime.date.today())
or
visitor.objects.filter(day_visiting=datetime.date.today()).count()
yesterday search
today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
visitor.objects.get(day_visiting=today)
or
visitor.objects.filter(day_visiting=yesterday).count()

8. object delete

outdated_day = today - datetime.timedelta(days = 30)
obs = visitor_ss2r.objects.filter(day_visiting=outdated_day)
if len(obs) > 0:
    obs.delete()


9. admin page DB field view

Add def __str__(self): .....  show below code!

class visitor_ss2r(models.Model):
    id = models.AutoField(primary_key=True)
    count = models.PositiveIntegerField(default=0)
    day_visiting = models.DateField(auto_now=True)

    def __str__(self):
        return 'Date: ' + str(self.day_visiting)

then you can see like that in admin page


more detail
in admin.py, we can make column list like that:

class visitor_ss2r_Admin(admin.ModelAdmin):
    list_display = ('id', 'count', 'day_visiting')
admin.site.register(visitor_ss2r, visitor_ss2r_Admin)



R. reference

Fastest way to get the first object from a queryset in django?https://stackoverflow.com/questions/5123839/fastest-way-to-get-the-first-object-from-a-queryset-in-django

Making queries (Django officials page)
https://docs.djangoproject.com/en/2.0/topics/db/queries/