Django Shoho

It's a Mac.

environment

Create an environment with venv and install django. $python -m venv <environmentName> $cd <environmentName> $source bin/activate $pip install --upgrade pip $pip install django==2.0.1 $django-admin startproject <projectName> . $python manage.py startapp <applicationName> At the end of 2019, django is version 3 series. If you install it without doing anything, it will happen and you may not be able to log in to admin, so it is safe to use 2 system.

I will go below. environmentName = reh projectName = rehabili applicationName = reha

Tweak Django's preferences in settings.py.

python:rehabili/python:setting.py


# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ja'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Tokyo'

### Create to database `python manage.py migrate`
### Add superuser `python manage.py createsuperuser` Follow the instructions as appropriate.
### Start development server `python manage.py runserver`

Open http://127.0.0.1:8000/ or http: // localhost: 8000 / with a browser and succeed if the rocket comes out


### Creating a model

reh/models.py


from django.db import models


class SamplePost(models.Model):
    postname = models.CharField('name', max_length=999)
    postfrom = models.CharField('from', max_length=999, blank=True)
    postlength = models.IntegerField('length', blank=True, default=0)

    def __str__(self):
        return self.postname


class SamplePost2(models.Model):
    postname2 = models.ForeignKey(SamplePost, verbose_name='postname', related_name='samplepost2', on_delete=models.CASCADE)
    comment = models.TextField('comment', blank=True)

    def __str__(self):
        return self.comment

Added to management screen

reh/admin.py


from django.contrib import admin
from reh.models import SamplePost, SamplePost2

admin.site.register(SamplePost)
admin.site.register(SamplePost2)

Add app

python:rehabili/python:setting.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'reh', #Add the created app name here
]

Pre-process to add to the database with makemigratoins. You don't have to have the last application name, but it will probably get longer as the project grows. `python manage.py makemigrations reh`
Add to database `python manage.py migrate`

Log in to the management screen

Log in with the superuser you created earlier http://localhost:8000/admin/ Screen Shot 2019-12-31 at 13.51.38.png

Fixed management screen

I referred to here. Items that can be modified will increase from the list on the management screen. https://qiita.com/kaki_k/items/7b178ad39394a031b50d

reh/admin.py


from django.contrib import admin
from reh.models import SamplePost, SamplePost2


class SamplePostAdmin(admin.ModelAdmin):
    list_display = ('id', 'postname', 'postfrom', 'postlength',)  #Items you want to list
    list_display_links = ('id', 'postname',)  #Items that can be clicked with the correction link

admin.site.register(SamplePost, SamplePostAdmin)


class SamplePost2Admin(admin.ModelAdmin):
    list_display = ('id', 'comment',)
    list_display_links = ('id', 'comment',)
    raw_id_fields = ('postname2',)   #Do not pull down the foreign key (prevent timeout when the number of data increases)

admin.site.register(SamplePost2, SamplePost2Admin)

URL scheme design

Create urls.py in your app folder and include it from your project's urls.py.

reh/views.py


from django.shortcuts import render
from django.http import HttpResponse


def reh_list(request):
    return HttpResponse('reh list')

reh/urls.py


from django.urls import path
from reh import views

app_name = 'reh'
urlpatterns = [
    path('list/', views.reh_list, name='reh_list'),
]

rehabili/urls.py


from django.contrib import admin
from django.urls import path, include

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

The following URL will come alive http://127.0.0.1:8000/reh/list/

Make a form

Turn a little sideways and make the foam normally. However, this method cannot be reflected in the DB.

reh/views.py



###P.S
def formInit(request):
    params = {
        'title':'Hello World',
        'msg':'Please enter your name',
    }
    return render(request,'reh/hello.html', params)



def formTest(request):
    msg = request.POST['msg']
    params = {
        'title':'Hello World',
        'msg':'hello '+msg+'!',
    }
    return render(request,'reh/hello.html', params)

reh/urls.py


from django.urls import path
from reh import views

app_name = 'reh'
urlpatterns = [
    path('list/', views.reh_list, name='reh_list'),
    path('formInit/', views.formInit, name='formInit'),
    path('formTest/', views.formTest, name='formTest'),
]

reh/template/reh/hello.html


{% load static %}
<!doctype html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title }}</h1>   
        <p>{{ msg }}</p>
        <!--Specify the action as you would in normal HTML-->
        <form action="{% url 'reh:formTest' %}" method = "post"> 
            {% csrf_token %} <!--CSRF measures-->
            <label for = "msg">Put something in</label>
            <input id = "msg" type="text" name ="msg">
            <input type="submit" value="input">
        </form>
    </body>
</html>

dddd.jpg

It works normally only on the browser. Since it cannot be reflected in the DB as it is, use Django's forms.py and Form classes. Write only the difference part.

reh/views.py


from .forms import formInitForm

def formInit(request):
    # params = {
    #     'title':'Hello World',
    #     'msg':'Please enter your name',
    # }
    # return render(request,'reh/hello.html', params)

    params = {
        'title':'Hello World',
        'msg':'Please enter your name',
        'form': formInitForm(),
    }
    if (request.method=='POST'):
        params['msg'] = 'Hello!'+request.POST['name']+'Mr.!<br>'+request.POST['area']+'Live in<br>Age is'+request.POST['age']+'I'm old!<br>Thank you.'
        params['form']= formInitForm(request.POST)

    return render(request,'reh/hello.html', params)    

# def formTest(request):
#     msg = request.POST['msg']
#     params = {
#         'title':'Hello World',
#         'msg':'hello '+msg+'!',
#     }
#     return render(request,'reh/hello.html', params)


reh/urls.py


    path('formInit/', views.formInit, name='formInit'),
    # path('formTest/', views.formTest, name='formTest'),

Even if you comment out the template, the python inside will be executed, so please check the differences yourself.

reh/template/reh/hello.html


{% load static %}
<!doctype html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title }}</h1>   

        <p>{{msg|safe}}</p>     
        <form action= "{% url 'reh:formInit' %}" method = "post"> 
            {% csrf_token %} 
            <ul>
            {{form.as_ul}} <!--Here are forms.py item-->    
            </ul>
            <input type="submit" value="input"> 
        </form>

    </body>
</html>

aaa.jpg

CRUD/ create, read, update, delete Now, let's go back from the side street so that we can modify, delete, and add from the list. First, make a list.

I will make some template html, so I will make a base. I guess css appropriately.

reh/template/reh/base.html


{% load i18n static %}
<!DOCTYPE html>{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE|default:'en-us' }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
h4{
  font-size: 20px;
  display: inline-block;
  margin-right: 30px;
}
.container{
    width: 100%;
    max-width: 800px;
    margin: 60px auto;
}
.btn{
  text-decoration: none;
    padding: 5px 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}
button.btn{
    font-size: 16px;
    display: inline-block;
    line-height: 1;
}
th,td{
  min-width: 100px;
  text-align: center;
}
table{
  border-collapse:collapse;
  margin:0 auto;
}
th{
  color:#005ab3;
  min-width: 120px;
}
td{
  border-bottom:1px dashed #999;
}
th,tr:last-child td{
  border-bottom:2px solid #005ab3;
}
td,th{
  padding:10px;
}
form input{
  padding: 5px;
    font-size: 20px;
    margin-bottom: 20px;
}
form label{
    padding: 5px;
    font-size: 20px;
    margin-bottom: 20px;
    min-width: 90px;
    display: inline-block;
}
.flex{
  display: flex;
}
</style>
{% block extra_css %}{% endblock %}
<title>{% block title %}My rehs{% endblock %}</title>
</head>
<body>
  <div class="container">
    {% block content %}
      {{ content }}
    {% endblock %}
  </div>
{% block extra_js %}{% endblock %}
</body>
</html>

reh/template/reh/reh_list.html


{% extends "reh/base.html" %}

{% block title %}List{% endblock title %}

{% block content %}
    <h4>List</h4>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">NAME</th>
          <th scope="col">FROM</th>
          <th scope="col">LENGTH</th>
        </tr>
      </thead>
      <tbody>
        {% for reh in rehs %} <!-- ① -->
        <tr>
          <th scope="row">{{ reh.id }}</th>
          <td>{{ reh.postname }}</td>
          <td>{{ reh.postfrom }}</td>
          <td>{{ reh.postlength }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
{% endblock content %}

① Since the list is read in the part of {% for reh in rehs%}, modify views.py.

reh/views.py


def reh_list(request):
#    return HttpResponse('List')

    #Here, bring all SamplePosts in id order and store them in rehs.
    rehs = SamplePost.objects.all().order_by('id')

    #Since you can put a dictionary in the third argument of the render method, put rehs with the name rehs brought above.
    return render(request, 'reh/reh_list.html', {'rehs': rehs})

You should now see the list at http: // localhost: 8000 / reh / list /.

Then create an add button.

reh/template/reh/reh_list.html


{% extends "reh/base.html" %}

{% block title %}List{% endblock title %}

{% block content %}
    <h4>List</h4>
    <!--Add here-->
    <a href="{% url 'reh:reh_add' %}" class="btn">add to</a>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">NAME</th>
          <th scope="col">FROM</th>
          <th scope="col">LENGTH</th>
        </tr>
      </thead>
      <tbody>
        {% for reh in rehs %} <!-- ① -->
        <tr>
          <th scope="row">{{ reh.id }}</th>
          <td>{{ reh.postname }}</td>
          <td>{{ reh.postfrom }}</td>
          <td>{{ reh.postlength }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
{% endblock content %}

{% url'reh: reh_add'%} Add reh_add to urls.py. Add a view called reh_edit. Call reh_edit in views.py.

reh/urls.py


path('list/add/', views.reh_edit, name='reh_add'),

reh/views.py


def reh_edit(request, reh_id=None):
    reh_temp = SamplePost()

    if request.method == 'POST':
        #Processing when POSTing a form on an additional page
        form = SamplePostForm(request.POST, instance=reh_temp)
        #Validation of POSTed form
        if form.is_valid():
            reh_temp = form.save(commit=False)
            reh_temp.save()
            #When the form is saved, it will return to the list.
            return redirect('reh:reh_list')

    else: #This is displayed when the add button is pressed from the list at the time of GET.
        #Create a form from a SamplePost instance
        form = SamplePostForm(instance=reh_temp)

    #Form and reh in the dictionary_id=Enter None and use the render method to transition the page for editing.
    return render(request, 'reh/reh_edit.html', dict(form=form, reh_id=reh_id))

Create a model of the above form in forms.py.

reh/forms.py


from django.forms import ModelForm
from reh.models import SamplePost

class SamplePostForm(ModelForm):
    #If you want to use the property already defined in SamplePost, use the Meta class.
    class Meta:
        model = SamplePost
        #When using only some properties of the model, either explicitly or
        fields = ('postname', 'postfrom', 'postlength', )

Create a page template for editing.

reh/template/reh/reh_edit.html


{% extends "reh/base.html" %}

{% block title %}title{% endblock title %}

{% block content %}
  <!--As a form action, reh the value of form_Send to edit view-->
  <form action="{% url 'reh:reh_add' %}" method="post">      
    {% csrf_token %}
    #Forms described below.Call py
    {{ form.as_ul }}
    <div>
      <button type="submit" class="btn">Send</button>
    </div>
  </form>
  <a href="{% url 'reh:reh_list' %}" class="btn">Return</a>
{% endblock content %}

Next, do a simple deletion (easy because it disappears suddenly on the confirmation screen)

Get the reh_id and erase it.

Add a button to the template and skip to the next view with id.

reh/template/reh/reh_list.html


{% extends "reh/base.html" %}

{% block title %}List{% endblock title %}

{% block content %}
    <h4>List</h4>
    <!--Add here-->
    <a href="{% url 'reh:reh_add' %}" class="btn">add to</a>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">NAME</th>
          <th scope="col">FROM</th>
          <th scope="col">LENGTH</th>
          <th scope="col">operation</th>
        </tr>
      </thead>
      <tbody>
        {% for reh in rehs %} <!-- ① -->
        <tr>
          <th scope="row">{{ reh.id }}</th>
          <td>{{ reh.postname }}</td>
          <td>{{ reh.postfrom }}</td>
          <td>{{ reh.postlength }}</td>
      <td>
            <!--reh to the link destination of the a tag_Set to del view and add ID to the argument-->
            <a href="{% url 'reh:reh_del' reh_id=reh.id %}" class="btn">Delete</a>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
{% endblock content %}

reh/views.py



def reh_del(request, reh_id):
    #If there is an instance with the specified ID, it will be specified, otherwise 404(django.http.Http404)call,
    #Then delete and redirect to the list.
    reh = get_object_or_404(SamplePost, pk=reh_id)
    reh.delete()
    return redirect('reh:reh_list')

This is the URL.

reh/urls.py


path('list/del/<int:reh_id>/', views.reh_del, name='reh_del'),

Finally, the fix button. Let's add a button to the list page.

reh/template/reh/reh_list.html


{% extends "reh/base.html" %}

{% block title %}List{% endblock title %}

{% block content %}
    <h4>List</h4>
    <!--Add here-->
    <a href="{% url 'reh:reh_add' %}" class="btn">add to</a>
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th scope="col">ID</th>
          <th scope="col">NAME</th>
          <th scope="col">FROM</th>
          <th scope="col">LENGTH</th>
          <th scope="col">operation</th>
        </tr>
      </thead>
      <tbody>
        {% for reh in rehs %} <!-- ① -->
        <tr>
          <th scope="row">{{ reh.id }}</th>
          <td>{{ reh.postname }}</td>
          <td>{{ reh.postfrom }}</td>
          <td>{{ reh.postlength }}</td>
      <td>
            <!--Add modification button This also has an id as an argument. Use the same view to add.-->
            <a href="{% url 'reh:reh_mod' reh_id=reh.id %}" class="btn ">Fix</a>
            <a href="{% url 'reh:reh_del' reh_id=reh.id %}" class="btn">Delete</a>
          </td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
{% endblock content %}

Modify reh_edit in views.py.

reh/views.py


def reh_edit(request, reh_id=None):
    #The case of addition and the case is whether id is required as an argument, so use it
    #reh_Whether temp has a value or not is the same process as adding
    if reh_id:
        #Processing when making corrections. Instance is an existing value
        reh_temp = get_object_or_404(SamplePost, pk=reh_id)
    else:
        #Processing when this is newly added. Instance is default
        reh_temp = SamplePost()

    if request.method == 'POST':
        form = SamplePostForm(request.POST, instance=reh_temp)
        if form.is_valid():
            reh_temp = form.save(commit=False)
            reh_temp.save()
            return redirect('reh:reh_list')

    else:
        form = SamplePostForm(instance=reh_temp)

    return render(request, 'reh/reh_edit.html', dict(form=form, reh_id=reh_id))

reh/urls.py


path('list/mod/<int:reh_id>/', views.reh_edit, name='reh_mod'),

The page template for editing is not only added but also modified.

reh/template/reh/reh_edit.html


{% extends "reh/base.html" %}

{% block title %}title{% endblock title %}

{% block content %}
    <!-- views.Like py, reh_Judge by the presence or absence of id-->
    {% if reh_id %}
    <form action="{% url 'reh:reh_mod' reh_id=reh_id %}" method="post">
    {% else %}
    <form action="{% url 'reh:reh_add' %}" method="post">
    {% endif %}
      {% csrf_token %}
      <ul>
      {{ form.as_ul }}
      </ul>
      <div class="flex">
          <button type="submit" class="btn">Send</button>
          <a href="{% url 'reh:reh_list' %}" class="btn">Return</a>
      </div>
    </form>
{% endblock content %}

I think you have created something like the following. Screen Shot 2020-01-02 at 16.52.02.png

Screen Shot 2020-01-02 at 16.52.12.png

Recommended Posts

Django Shoho
django update
Django note 4
Django memorandum
django search
Django installation
Django Summary
Django test
Django # 2 (template)
Django hands-on
Touch django
django notes
Django Summary
Django basics
Django defaults
Django + Docker
Django Glossary
Django search
Install Django
Django: References
Django Note 1
Django note 3
Django note 2
Django startup
Django notes
Django NullCharField
Django environment construction
Django ~ settings.py edition ~
Django Heroku Deploy 1
Django HTML Template # 2
Django Contact Form 2
Django begins part 1
Django model: ManyToManyField
What is Django? .. ..
Models in Django
Django function-based view
Python Django Tutorial (5)
Python Django Tutorial (2)
[Django] as_view () notes
First Django Challenge
django makemigarations createsuperuser
Django related sites
Internationalization with django
Django version check
django table creation
Django begins part 4
Django 1.9 for internationalization
CentOS8 --Play --Django
CentOS8 --Install --Django
[Django] Redo migrate
django environment construction
Django Template notes
Python Django Tutorial (8)
Python Django Tutorial (6)
django default settings
Start Django Tutorial 1
Django HTML template
Django Template Tips
Django girls-3 workflow
Django Project Baseline
Django Heroku Deploy 2