# Create your models here.
from django.db import models
import datetime
JST = datetime.timezone(datetime.timedelta(hours=9))
# Create your models here.
class SampleListModel(models.Model):
title = models.CharField('タイトル',max_length=50)
text = models.TextField('本文')
url = models.URLField('URL', blank=True)
created_at = models.DateTimeField('作成日', default=datetime.datetime.now(tz=JST))
def __str__(self):
return self.title
class SampleDetailModel(models.Model):
name = models.CharField('名前',max_length=256)
feature = models.TextField('特徴')
list = models.ForeignKey(SampleListModel, on_delete=models.CASCADE, related_name='related_list')
def __str__(self):
return self.name
forms.py
forms.py
from .models import SampleListModel, SampleDetailModel
from django.db import models
from django import forms
class SampleListForm(forms.ModelForm):
class Meta:
model = SampleListModel
fields = "__all__"
def __init__(self, *args, **kwargs):
for field in self.base_fields.values():
field.widget.attrs["class"]="form-control"
super().__init__(*args, **kwargs)
class SampleDetailForm(forms.ModelForm):
class Meta:
model = SampleDetailModel
fields = "__all__"
def __init__(self, *args, **kwargs):
for field in self.base_fields.values():
field.widget.attrs["class"]="form-control"
super().__init__(*args, **kwargs)
views.py
views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import CreateView, ListView, DetailView
from .models import SampleListModel, SampleDetailModel
from .forms import SampleListForm, SampleDetailForm
from django.urls import reverse, reverse_lazy
# Create your views here.
class SampleListCreate(CreateView):
template_name = 'app/list_create.html'
form_class = SampleListForm
success_url = reverse_lazy('app:app/list')
class SampleDetailCreate(CreateView):
template_name = 'app/detail_create.html'
form_class = SampleDetailForm
success_url = reverse_lazy('app:app/list')
class SampleList(ListView):
model = SampleListModel
context_object_name = "sample_list"
template_name = 'app/list.html'
class SampleDetail(DetailView):
model = SampleListModel
context_object_name = "sample_detail"
template_name = "app/detail.html"
pj/urls.py
pj/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls')),
]
コメント