如何实现MySQL网站中用户私有联系人信息的独立CRUD功能(Django)
Hey there! Great call avoiding per-user tables—they’re a total maintenance nightmare. Let’s walk through how to set up isolated contact lists for each user using Django and MySQL, following best practices.
Instead of creating a new table for every user, we’ll use foreign keys to link contacts to their respective owners. Here’s the simple structure:
- Use Django’s built-in
auth_usertable (or your custom user table) to store user accounts (userid, username, email, password—exactly what you’re already saving). - Create a single
contactstable with fields for contact details (name, phone, email) plus auser_idcolumn that acts as a foreign key pointing to theauth_user.idcolumn. This ties every contact to one specific user.
Django makes this super straightforward with its ORM. Define your Contact model like this:
from django.db import models from django.contrib.auth.models import User class Contact(models.Model): # Link each contact to a user; delete contacts if their user is deleted user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="contacts") name = models.CharField(max_length=100) phone = models.CharField(max_length=20) email = models.EmailField() def __str__(self): return self.name # Makes admin view cleaner
Run these commands to create the table in MySQL:
python manage.py makemigrations python manage.py migrate
The key to data isolation is always filtering contacts by the currently logged-in user. Use Django’s request.user object to ensure users only access their own data.
First, create a simple form for contact inputs:
# forms.py from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ["name", "phone", "email"] # Only expose contact fields, not the user link
Then build your CRUD views with user filtering:
# views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from .models import Contact from .forms import ContactForm # Require login for all contact views @login_required def contact_list(request): # Only fetch contacts belonging to the logged-in user contacts = Contact.objects.filter(user=request.user) return render(request, "contacts/list.html", {"contacts": contacts}) @login_required def add_contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): # Create the contact but don't save yet—add the user first contact = form.save(commit=False) contact.user = request.user contact.save() return redirect("contact_list") else: form = ContactForm() return render(request, "contacts/add.html", {"form": form}) @login_required def edit_contact(request, pk): # Ensure the contact belongs to the current user (404 if not) contact = get_object_or_404(Contact, pk=pk, user=request.user) if request.method == "POST": form = ContactForm(request.POST, instance=contact) if form.is_valid(): form.save() return redirect("contact_list") else: form = ContactForm(instance=contact) return render(request, "contacts/edit.html", {"form": form}) @login_required def delete_contact(request, pk): contact = get_object_or_404(Contact, pk=pk, user=request.user) if request.method == "POST": contact.delete() return redirect("contact_list") return render(request, "contacts/delete.html", {"contact": contact})
- The
@login_requireddecorator ensures only logged-in users can access these views. - For your frontend templates, you can loop through the filtered contacts and add edit/delete buttons. Example list template:
<!-- contacts/list.html --> <h1>Your Private Contacts</h1> <a href="{% url 'add_contact' %}">Add New Contact</a> <ul> {% for contact in contacts %} <li> {{ contact.name }} | {{ contact.phone }} | {{ contact.email }} <a href="{% url 'edit_contact' contact.pk %}">Edit</a> <form action="{% url 'delete_contact' contact.pk %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit">Delete</button> </form> </li> {% empty %} <li>No contacts yet—add your first one!</li> {% endfor %} </ul>
- Foreign keys are your friend: They create the link between users and their contacts without messy per-user tables.
- Always filter by
request.user: This is the critical step to prevent users from accessing others’ data. - Leverage Django’s auth system: It handles login/registration out of the box, so you don’t have to reinvent that wheel (though you can customize it if needed).
内容的提问来源于stack exchange,提问作者X-TremeFighter12

