如何在Django中实现表单自动记录已登录用户的预约数据?
Hey there! Let's fix your booking form so it automatically links submissions to the logged-in user. I'll walk you through each step with code examples tailored to Django (since you mentioned forms.py, models.py, views.py—that's the telltale sign!).
1. Update Your models.py to Track the User
First, we need to add a field to your Booking model that links it to the authenticated user. This creates a direct relationship between bookings and the users who made them:
from django.db import models from django.contrib.auth.models import User class Booking(models.Model): date = models.DateField() students = models.IntegerField() length = models.DurationField() # Adjust field type if you're using something like IntegerField for minutes # Add the user association user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="bookings" # Lets you access a user's bookings via user.bookings ) def __str__(self): return f"Booking on {self.date} by {self.user.username}"
After adding this, run python manage.py makemigrations and python manage.py migrate to update your database schema.
2. Adjust forms.py to Hide the User Field
Users shouldn't have to manually select themselves in the form, so we'll exclude the user field from the form's visible fields. If you're using a ModelForm, this is straightforward:
from django import forms from .models import Booking class BookingForm(forms.ModelForm): class Meta: model = Booking # Only include fields users need to fill out fields = ["date", "students", "length"] # Alternatively, use exclude = ["user"] to omit the field
3. Modify views.py to Auto-Assign the Logged-In User
Now we need to inject the current user into the booking when the form is submitted. We'll also ensure only logged-in users can submit bookings (you can skip the login requirement if you allow anonymous bookings, but that's rare for reservation systems).
Option 1: Function-Based View
from django.shortcuts import render, redirect from .forms import BookingForm from django.contrib.auth.decorators import login_required @login_required # Blocks access to non-logged-in users def create_booking(request): if request.method == "POST": form = BookingForm(request.POST) if form.is_valid(): # Create the booking instance but don't save to DB yet booking = form.save(commit=False) # Assign the current logged-in user booking.user = request.user # Now save the complete booking to the database booking.save() return redirect("booking_success") # Replace with your success page URL name else: form = BookingForm() return render(request, "booking_form.html", {"form": form})
Option 2: Class-Based View (CreateView)
If you prefer class-based views, use LoginRequiredMixin to enforce login and override form_valid to add the user:
from django.views.generic.edit import CreateView from .models import Booking from .forms import BookingForm from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy class BookingCreateView(LoginRequiredMixin, CreateView): model = Booking form_class = BookingForm success_url = reverse_lazy("booking_success") # Uses reverse_lazy to avoid URL resolution issues def form_valid(self, form): # Attach the current user to the booking instance form.instance.user = self.request.user return super().form_valid(form)
4. Verify It Works
After setting this up, submit a booking while logged in, then check your bookings table (via Django Admin or python manage.py shell)—you'll see the user column is now populated with the correct user ID and associated user data.
A quick note: If you're using a custom user model instead of Django's default User, replace from django.contrib.auth.models import User with an import of your custom model, and update the ForeignKey to point to it.
内容的提问来源于stack exchange,提问作者Adam Dalton

