tiancheng91 / collection

笔记
https://github.com/tiancheng91/collection/issues
22 stars 1 forks source link

django #26

Open tiancheng91 opened 5 years ago

tiancheng91 commented 5 years ago

:scroll: Django Cheat Sheet

A cheat-sheet for creating web apps with the Django framework using the Python language. Most of the summaries and examples are based off the official documentation for Django v2.0.

Sections

:snake: Initializing pipenv (optional)

:blue_book: Creating a project

The project directory should look like this:

project/
    manage.py
    project/
        __init__.py
        settings.py
        urls.py
        wsgi.py

:page_with_curl: Creating an app

The project directory should now look like this:

project/
    manage.py
    db.sqlite3
    project/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    app/
        migrations/
            __init__.py
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
        urls.py
        views.py

:tv: Creating a view

def index(request): return HttpResponse("Hello, World!")

- Still within the app directory, open (or create)  `urls.py` 
```python
from django.urls import path
from . import views

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

urlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ]

- To create a url pattern to the index of the site, use the following urlpattern:
```python
urlpatterns = [
    path("", include('app.urls')),
]

:art: Creating a template

def index(request): return render(request,'index.html')

- To include context to the template:
```python
def index(request):
    context = {"context_variable": context_variable}
    return render(request,'index.html', context)

<!DOCTYPE html>

- To make sure to include the following in your `settings,py`:
```python
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

{% block content %}

Hello, World!

{% endblock %}

- And then in `base.html` add:
```html
<body>
    {% block content %}{% endblock %}
</body>

:ticket: Creating a model

class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)

*Note that you don't need to create a primary key, Django automatically adds an IntegerField.*

- To inact changes in your models, use the following commands in your shell:

$ python manage.py makemigrations $ python manage.py migrate

*Note: including <app_name> is optional.*
- A one-to-many relationship can be made with a `ForeignKey`:
```python
class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

class Pizza(models.Model):

...

toppings = models.ManyToManyField(Topping)
*Note that the `ManyToManyField`  is **only defined in one model**. It doesn't matter which model has the field, but if in doubt, it should be in the model that will be interacted with in a form.*

- Although Django provides a `OneToOneField` relation, a one-to-one relationship can also be defined by adding the kwarg of `unique = True` to a model's `ForeignKey`:
```python
ForeignKey(SomeModel, unique=True)

:postbox: Creating model objects and queries

class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField()

def __str__(self):
    return self.name

class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField()

def __str__(self):
    return self.name

class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) n_comments = models.IntegerField() n_pingbacks = models.IntegerField() rating = models.IntegerField()

def __str__(self):
    return self.headline
- To create an object within the shell:

$ python manage.py shell

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

:man: Using the Admin page

admin.site.register(Author) admin.site.register(Book)

tiancheng91 commented 5 years ago

https://djangopackages.org/

starter

https://github.com/crowdbotics-apps/koding-3860

tiancheng91 commented 5 years ago
strace -p pid