我正在尝试制作一个编辑用户个人资料表单,我的问题是,如果我不从表单中排除用户,它会要求它,但如果我排除它我会得到:
错误:
IntegrityError at /apps/edit-profile
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (21, 85.75, Alexe, Bogdan, null, Romania, null, null, null, null).
models.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
balance = models.DecimalField(max_digits=6, decimal_places=2, default=0.00, blank=True, null=True)
first_name = models.CharField(max_length=200, blank=True, null=True, default=None)
last_name = models.CharField(max_length=200, blank=True, null=True, default=None)
forms.py
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = '__all__'
exclude = ('user', )
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
views.py
@login_required
def user_profile(request):
data = dict()
if request.method == 'POST':
profile = get_object_or_404(UserProfile, user=request.user)
form = UserProfileForm(request.POST, profile)
if form.is_valid():
profile = form.save(commit=False)
profile.balance = Income.objects.filter(assigned_to__username=request.user).aggregate(sum=Sum('value'))['sum']
profile.save()
return redirect('/apps/home')
else:
form = UserProfileForm()
data['form'] = form
return render(request, 'core/profile.html', data)
profile.html
<form class="js-validation-bootstrap" action="" method="post">
{% csrf_token %}
{{ form.errors }}
<div class="form-group row">
<label class="col-lg-4 col-form-label" for="val-username">First Name </label>
<div class="col-lg-8">
<input type="Text" class="form-control" id="val-username" name="first_name" placeholder="">
</div>
</div>
<div class="form-group row">
<label class="col-lg-4 col-form-label" for="val-username">Last Name </label>
<div class="col-lg-8">
<input type="Text" class="form-control" id="val-username" name="last_name" placeholder="">
</div>
</div>
<div class="col-lg-8 ml-auto">
<button type="Submit" class="btn btn-alt-primary">Submit</button>
</div>
</div>
</form>
我不明白为什么它会给我这个错误。
答案 0 :(得分:3)
您可以在视图中添加当前用户,即使此字段已排除在外:
profile = form.save(commit=False)
profile.user = request.user
profile.save()