我在我的一个基于班级的观点中继续这样做:
if form.is_valid():
form.save(commit=False)
form.manager = User.objects.get(username=request.user.username)
form.save()
location = Location.objects.get(name=form.cleaned_data['name'])
user.get_profile().owned_locations.add(location)
return redirect(reverse('location_manager'))
然而,当我填写表格时,我收到以下错误:
IntegrityError at /dash/location/add
locationmanager_location.manager_id may not be NULL
这很奇怪,因为我的位置模型看起来像这样:
class Location(models.Model):
region = models.ForeignKey(Region)
manager = models.ForeignKey(User)
name = models.CharField(max_length=255)
street_address = models.TextField(blank=True)
city = models.CharField(max_length=255, blank=True)
zip_code = models.CharField(max_length=20, blank=True)
我的Forms.py看起来像这样:
class locationForm(forms.ModelForm):
class Meta:
model = Location
fields = (
'region',
'name',
'street_address',
'city',
'zip_code',
)
exclude =('manager',)
我似乎无法弄清楚这里的问题是什么。如果你很好奇为什么我有排除,我会听从丹尼尔罗斯曼的一些建议here
答案 0 :(得分:3)
而不是:
form.save(commit=False)
form.manager = User.objects.get(username=request.user.username)
form.save()
尝试:
obj = form.save(commit=False)
obj.manager = User.objects.get(username=request.user.username)
obj.save()
希望这些有帮助!
答案 1 :(得分:2)
您的表单处理稍有不正确,您应该这样做:
if form.is_valid():
instance = form.save(commit=False)
instance.manager = User.objects.get(username=request.user.username)
instance.save()
location = Location.objects.get(name=form.cleaned_data['name'])
user.get_profile().owned_locations.add(location)
return redirect(reverse('location_manager'))