Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,8 @@
USE_TZ = True
STATIC_URL = "static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
MEDIA_URL = "media/"
MEDIA_ROOT = BASE_DIR / "media"

LOGIN_URL = "/accounts/login/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
4 changes: 4 additions & 0 deletions config/urls.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path

Expand All @@ -10,3 +12,5 @@
path("diary/", include("diary.urls")),
]

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
9 changes: 9 additions & 0 deletions records/admin.py
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
from django.contrib import admin

from .models import Record


@admin.register(Record)
class RecordAdmin(admin.ModelAdmin):
list_display = ("id", "user", "weather", "place_name", "created_at")
list_filter = ("weather", "created_at")
search_fields = ("user__username", "content", "place_name")
58 changes: 57 additions & 1 deletion records/forms.py
Original file line number Diff line number Diff line change
@@ -1 +1,57 @@
# 담당 C: 기록 작성, 수정 및 이미지 업로드 폼
from django import forms

from .models import Record


class RecordForm(forms.ModelForm):
emotions = forms.MultipleChoiceField(
Comment thread
dahliare marked this conversation as resolved.
choices=[(str(number), f"감정 {number}") for number in range(1, 21)],
required=True,
error_messages={"required": "감정을 1개 이상 선택해 주세요."},
)
main_emotion = forms.ChoiceField(
choices=[
("", "메인 감정 선택"),
*[
(str(number), f"감정 {number}")
for number in range(1, 21)
],
],
required=True,
error_messages={"required": "대표 감정을 선택해 주세요."},
)

class Meta:
model = Record
fields = [
"weather", "content", "image", "emotions", "main_emotion",
"place_name", "latitude", "longitude",
]

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk and not self.is_bound:
self.initial["emotions"] = [
str(emotion) for emotion in self.instance.emotions
]
self.initial["main_emotion"] = str(self.instance.main_emotion)

def clean_emotions(self):
emotions = self.cleaned_data.get("emotions", [])
if len(emotions) > 3:
raise forms.ValidationError("감정은 최대 3개까지 선택할 수 있습니다.")
return [int(emotion) for emotion in emotions]

def clean_main_emotion(self):
return int(self.cleaned_data["main_emotion"])

def clean(self):
cleaned_data = super().clean()
emotions = cleaned_data.get("emotions", [])
main_emotion = cleaned_data.get("main_emotion")
if main_emotion is not None and main_emotion not in emotions:
self.add_error(
"main_emotion",
"선택한 감정 중에서 대표 감정을 골라주세요.",
)
return cleaned_data
36 changes: 36 additions & 0 deletions records/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Generated by Django 6.0.7 on 2026-07-31 14:14

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Record',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('weather', models.CharField(choices=[('sunny', '해'), ('cloudy', '구름'), ('rainy', '비'), ('thunder', '천둥'), ('dust', '황사'), ('snowy', '눈')], max_length=10)),
('content', models.TextField(max_length=500)),
('image', models.ImageField(blank=True, upload_to='records/%Y/%m/%d/')),
('emotions', models.JSONField(default=list)),
('place_name', models.CharField(blank=True, max_length=100)),
('latitude', models.DecimalField(blank=True, decimal_places=7, max_digits=10, null=True)),
('longitude', models.DecimalField(blank=True, decimal_places=7, max_digits=10, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='heartmark_records', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created_at'],
},
),
]
18 changes: 18 additions & 0 deletions records/migrations/0002_alter_record_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 6.0.7 on 2026-08-01 13:55

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('records', '0001_initial'),
]

operations = [
migrations.AlterField(
model_name='record',
name='image',
field=models.ImageField(upload_to='records/%Y/%m/%d/'),
),
]
42 changes: 42 additions & 0 deletions records/migrations/0003_record_main_emotion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import migrations, models


def set_existing_main_emotions(apps, schema_editor):
Record = apps.get_model("records", "Record")
for record in Record.objects.all().iterator():
emotions = record.emotions if isinstance(record.emotions, list) else []
if not emotions:
emotions = [1]
record.emotions = emotions
record.main_emotion = int(emotions[0])
record.save(update_fields=["emotions", "main_emotion"])


class Migration(migrations.Migration):
dependencies = [
("records", "0002_alter_record_image"),
]

operations = [
migrations.AddField(
model_name="record",
name="main_emotion",
field=models.PositiveSmallIntegerField(
blank=True,
null=True,
validators=[MinValueValidator(1), MaxValueValidator(20)],
),
),
migrations.RunPython(
set_existing_main_emotions,
migrations.RunPython.noop,
),
migrations.AlterField(
model_name="record",
name="main_emotion",
field=models.PositiveSmallIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(20)],
),
),
]
76 changes: 75 additions & 1 deletion records/models.py
Original file line number Diff line number Diff line change
@@ -1 +1,75 @@
# 담당 C: Record 생성, 상세, 수정, 삭제
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class Record(models.Model):
class Weather(models.TextChoices):
SUNNY = "sunny", "해"
CLOUDY = "cloudy", "구름"
RAINY = "rainy", "비"
THUNDER = "thunder", "천둥"
DUST = "dust", "황사"
SNOWY = "snowy", "눈"

user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="heartmark_records",
)
weather = models.CharField(max_length=10, choices=Weather.choices)
content = models.TextField(max_length=500)
image = models.ImageField(upload_to="records/%Y/%m/%d/")
emotions = models.JSONField(default=list)
Comment thread
dahliare marked this conversation as resolved.
main_emotion = models.PositiveSmallIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(20)],
)

# TODO: locations.Place 규격 확정 후 ForeignKey 연결을 검토합니다.
place_name = models.CharField(max_length=100, blank=True)
latitude = models.DecimalField(max_digits=10, decimal_places=7, null=True, blank=True)
longitude = models.DecimalField(max_digits=10, decimal_places=7, null=True, blank=True)

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
ordering = ["-created_at"]

def __str__(self):
return f"{self.user}의 기록 ({self.created_at:%Y-%m-%d})"

@property
def weather_image_name(self):
return f"{self.weather}.png"

@property
def emotion_image_names(self):
return [f"emotion-{int(number):02d}.png" for number in self.emotions]

@property
def emotion_items(self):
numbers = [int(number) for number in self.emotions]
numbers.sort(key=lambda number: number != self.main_emotion)
return [
{
"number": number,
"image_name": f"emotion-{number:02d}.png",
"is_main": number == self.main_emotion,
}
for number in numbers
]

def clean(self):
super().clean()
if not isinstance(self.emotions, list):
raise ValidationError({"emotions": "감정은 목록 형태여야 합니다."})
if not self.emotions:
raise ValidationError({"emotions": "감정을 1개 이상 선택해 주세요."})
if len(self.emotions) > 3:
raise ValidationError({"emotions": "감정은 최대 3개까지 선택할 수 있습니다."})
if self.main_emotion not in self.emotions:
raise ValidationError({
"main_emotion": "선택한 감정 중에서 대표 감정을 골라주세요."
})
Loading