Django ValueError:无法为HotelConfirm.username分配默认User实例
问题
在Django项目中,尝试将用户实例分配给HotelConfirm模型的username字段时遇到ValueError,错误信息:
Cannot assign "<SimpleLazyObject: <User: gouri24>>": "HotelConfirm.username" must be a "userLogin" instance.
使用Django默认User模型,但username字段期望的是userLogin实例,传入的默认User实例不匹配。相关代码片段:
@login_required def book_hotel(request, hotel_id): hotel = get_object_or_404(Hotel, pk=hotel_id) if request.method == 'POST': # Process the form submission user_instance = request.user # Use the user instance directly room_type = request.POST.get('roomType') arrival = request.POST.get('arrival') departure = request.POST.get('departure') adult = request.POST.get('adult') children = request.POST.get('children') booking = HotelConfirm.objects.create( username=user_instance, hotel=hotel, roomType=room_type, arrival=arrival, departure=departure, adult=adult, children=children ) booking.save() # Save the booking object # Redirect to the home page after successful booking return redirect('home') # Replace 'home' with the actual name or URL of your home page return render(request, 'Booking_hotel.html', {'hotel_id': hotel_id})
解决方案
情况1:HotelConfirm模型应关联默认User模型
检查HotelConfirm模型定义,将username字段的外键指向Django默认User模型:
from django.contrib.auth.models import User class HotelConfirm(models.Model): # 修改外键指向默认User模型 username = models.ForeignKey(User, on_delete=models.CASCADE) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) # 其他字段定义...
修改后执行数据库迁移:
python manage.py makemigrations python manage.py migrate
情况2:确实需要使用userLogin自定义用户模型
如果项目依赖userLogin自定义用户模型,需根据它和默认User的关联关系获取对应实例:
- 假设
userLogin和User是一对一关联:
class userLogin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # 其他自定义字段...
- 在视图中获取当前用户对应的
userLogin实例:
# 替换原user_instance的赋值逻辑 user_instance = request.user.userlogin # 反向关联名由Django自动生成,若模型设置了related_name则用对应名称
额外优化点
- 视图中的
@login_required装饰器建议补全括号(Django 3.0+支持无括号,但显式写法更规范):@login_required() HotelConfirm.objects.create()方法会自动保存实例,无需额外调用booking.save()
内容的提问来源于stack exchange,提问作者Gouri krishna s
相关产品推荐
相关产品推荐

