Okay, let's outline a Django project for gym management focusing on the customer side. This will be a fairly comprehensive structure, and I'll provide code snippets for key parts. I'll focus on the core models, views, and URLs. Remember that a full project would involve more details like forms, templates, styling, and potentially more advanced features.
1. Project Setup
First, create a Django project and app:
django-admin startproject gym_management
cd gym_management
python manage.py startapp customers
2. customers/models.py
This is where we define the data models for our customers and related information.
from django.db import models
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
phone_number = models.CharField(max_length=20, blank=True, null=True) # Optional
date_of_birth = models.DateField(blank=True, null=True) # Optional
address = models.TextField(blank=True, null=True) # Optional
join_date = models.DateField(auto_now_add=True)
membership_type = models.CharField(max_length=50, choices=[
('basic', 'Basic'),
('premium', 'Premium'),
('gold', 'Gold'),
], default='basic')
# Add more fields as needed (e.g., emergency contact, medical conditions)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Attendance(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='attendances')
check_in_time = models.DateTimeField(auto_now_add=True)
check_out_time = models.DateTimeField(blank=True, null=True)
def __str__(self):
return f"{self.customer.first_name} - {self.check_in_time}"
class Payment(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='payments')
amount = models.DecimalField(max_digits=10, decimal_places=2)
payment_date = models.DateField(auto_now_add=True)
payment_method = models.CharField(max_length=50, choices=[
('cash', 'Cash'),
('card', 'Card'),
('online', 'Online'),
], default='cash')
# Add more fields as needed (e.g., transaction ID)
def __str__(self):
return f"{self.customer.first_name} - {self.amount} - {self.payment_date}"
Explanation of Models:
Customer: Stores customer information.
membership_type: Uses choices to restrict the possible membership types.
Attendance: Tracks when a customer checks in and out of the gym. related_name='attendances' allows you to easily access all attendance records for a customer (e.g., customer.attendances.all()).
Payment: Records customer payments. related_name='payments' allows you to access all payments for a customer.
3. customers/admin.py
Register the models with the Django admin interface for easy management.
from django.contrib import admin
from .models import Customer, Attendance, Payment
admin.site.register(Customer)
admin.site.register(Attendance)
admin.site.register(Payment)
4. customers/views.py
Create views to handle requests and display data.
from django.shortcuts import render, redirect, get_object_or_404
from .models import Customer, Attendance, Payment
from .forms import CustomerForm # We'll create this in the next step
def customer_list(request):
customers = Customer.objects.all()
return render(request, 'customers/customer_list.html', {'customers': customers})
def customer_detail(request, pk):
customer = get_object_or_404(Customer, pk=pk)
attendances = customer.attendances.all()
payments = customer.payments.all()
return render(request, 'customers/customer_detail.html', {'customer': customer, 'attendances': attendances, 'payments': payments})
def customer_create(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
return redirect('customer_list') # Redirect to the list view
else:
form = CustomerForm()
return render(request, 'customers/customer_form.html', {'form': form})
def customer_update(request, pk):
customer = get_object_or_404(Customer, pk=pk)
if request.method == 'POST':
form = CustomerForm(request.POST, instance=customer)
if form.is_valid():
form.save()
return redirect('customer_detail', pk=pk)
else:
form = CustomerForm(instance=customer)
return render(request, 'customers/customer_form.html', {'form': form})
def customer_delete(request, pk):
customer = get_object_or_404(Customer, pk=pk)
if request.method == 'POST':
customer.delete()
return redirect('customer_list')
return render(request, 'customers/customer_confirm_delete.html', {'customer': customer})
def check_in_customer(request, pk):
customer = get_object_or_404(Customer, pk=pk)
attendance = Attendance.objects.create(customer=customer)
return redirect('customer_detail', pk=pk)
def check_out_customer(request, pk, attendance_pk):
attendance = get_object_or_404(Attendance, pk=attendance_pk, customer__pk=pk)
attendance.check_out_time = timezone.now() # Import timezone from django.utils
attendance.save()
return redirect('customer_detail', pk=pk)
5. customers/forms.py
Create forms for handling customer data.
from django import forms
from .models import Customer
class CustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = ['first_name', 'last_name', 'email', 'phone_number', 'date_of_birth', 'address', 'membership_type']
6. customers/urls.py
Define the URL patterns for the app.
from django.urls import path
from . import views
urlpatterns = [
path('', views.customer_list, name='customer_list'),
path('<int:pk>/', views.customer_detail, name='customer_detail'),
path('create/', views.customer_create, name='customer_create'),
path('<int:pk>/update/', views.customer_update, name='customer_update'),
path('<int:pk>/delete/', views.customer_delete, name='customer_delete'),
path('<int:pk>/check_in/', views.check_in_customer, name='check_in_customer'),
path('<int:pk>/check_out/<int:attendance_pk>/', views.check_out_customer, name='check_out_customer'),
]
7. gym_management/urls.py
Include the customers app's URLs in the project's main URL configuration.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('customers/', include('customers.urls')),
]
8. Templates (HTML)
You'll need to create HTML templates for the views. Here are basic examples:
customers/customer_list.html:
<h1>Customer List</h1>
<ul>
{% for customer in customers %}
<li><a href="{% url 'customer_detail' pk=customer.pk %}">{{ customer }}</a></li>
{% endfor %}
</ul>
<a href="{% url 'customer_create' %}">Add New Customer</a>
customers/customer_detail.html:
<h1>Customer Details</h1>
<p>Name: {{ customer.first_name }} {{ customer.last_name }}</p>
<p>Email: {{ customer.email }}</p>
<p>Membership: {{ customer.membership_type }}</p>
<h2>Attendance</h2>
<ul>
{% for attendance in attendances %}
<li>Check-in: {{ attendance.check_in_time }}
{% if attendance.check_out_time %}
- Check-out: {{ attendance.check_out_time }}
{% else %}
- <a href="{% url 'check_out_customer' pk=customer.pk attendance_pk=attendance.pk %}">Check Out</a>
{% endif %}
</li>
{% endfor %}
</ul>
<a href="{% url 'check_in_customer' pk=customer.pk %}">Check In</a>
<h2>Payments</h2>
<ul>
{% for payment in payments %}
<li>Amount: {{ payment.amount }} - Date: {{ payment.payment_date }}</li>
{% endfor %}
</ul>
<a href="{% url 'customer_update' pk=customer.pk %}">Edit</a>
<a href="{% url 'customer_delete' pk=customer.pk %}">Delete</a>
customers/customer_form.html:
<h1>Customer Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
customers/customer_confirm_delete.html:
<h1>Confirm Delete</h1>
<p>Are you sure you want to delete {{ customer }}?</p>
<form method="post">
{% csrf_token %}
<button type="submit">Delete</button>
<a href="{% url 'customer_detail' pk=customer.pk %}">Cancel</a>
</form>
9. settings.py
Make sure you have 'customers' added to INSTALLED_APPS in your settings.py file.
Important Considerations and Next Steps:
- Styling: Use CSS to make the templates look presentable.
- Forms: Improve the forms with validation and better layout.
- Authentication: Implement user authentication (login/logout) for staff/admin access.
- Error Handling: Add error handling to the views.
- Security: Protect against common web vulnerabilities (CSRF, XSS, SQL injection).
- Testing: Write unit tests to ensure the code works correctly.
- More Features:
- Membership management (renewal, upgrades).
- Class scheduling.
- Reporting (revenue, attendance).
- Integration with payment gateways.
- User roles and permissions.
- Timezone: Make sure you're handling timezones correctly, especially for attendance records. Import
timezone from django.utils and use timezone.now() instead of datetime.now().
This provides a solid foundation for a gym management project. Remember to adapt and expand it based on your specific requirements. Let me know if you'd like me to elaborate on any particular aspect or provide more detailed code examples.