本篇文章介紹社團可以嘗試的活動類型,吸引學員來參加社團活動。
更新 models
from django.db import models
from django.contrib.auth.models import User
class Event(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
date = models.DateTimeField()
venue = models.CharField(max_length=100)
capacity = models.IntegerField()
def __str__(self):
return self.title
class Registration(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
event = models.ForeignKey(Event, on_delete=models.CASCADE)
registration_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.user.username} - {self.event.title}"
在event_registration/views.py
中
處理報名邏輯:
from django.shortcuts import render, redirect
from .models import Event, Registration
def event_list(request):
events = Event.objects.all()
return render(request, 'event_list.html', {'events': events})
def register_event(request, event_id):
if request.user.is_authenticated:
event = Event.objects.get(pk=event_id)
Registration.objects.create(user=request.user, event=event)
return redirect('event_list')
else:
return redirect('login')
在event_registration/urls.py
中 定義URL
from django.urls import path
from . import views
urlpatterns = [
path('', views.event_list, name='event_list'),
path('register/<int:event_id>/', views.register_event, name='register_event'),
]
在event_registration/templates
資料夾中,新增一個event_list.html
{% for event in events %}
<h3>{{ event.title }}</h3>
<p>{{ event.description }}</p>
<a href="{% url 'register_event' event.id %}">Register</a>
{% endfor %}
資料庫更新
python manage.py makemigrations event_registration
python manage.py migrate
執行
python manage.py runserver