[英]IntegrityError at /profile NOT NULL constraint failed: tutorapp_profile.user_id
I am making an app for finding tutors where tutors need to log in and post their jobs in the web application.我正在制作一个应用程序来寻找导师,导师需要登录并在 web 应用程序中发布他们的工作。 While developing the profile section for tutors, i am unable to add a feature of updating or uploading a new profile bio and profile picture.
在为导师开发个人资料部分时,我无法添加更新或上传新个人资料和个人资料图片的功能。 I'm new to django
我是 django 的新手
Here is my model of Profile in models.py这是我在models.py中的Profile的model
class Profile(models.Model):
user= models.OneToOneField(User, on_delete=models.CASCADE)
image= models.ImageField(default = 'default.jpg',upload_to='profile_pics')
bio=models.CharField(default = 'no bio',max_length=350)
def __str__ (self):
return f'{self.user.username} Profile'
and its model form及其 model 形式
class UpdateProfile(forms.ModelForm):
class Meta:
model = Profile
fields =['image','bio',]
def clean(self):
super(UpdateProfile, self).clean()
return self.cleaned_data
view of profile views.py个人资料views.py的视图
def profile(request):
if request.method == 'POST':
p_form = UpdateProfile(request.POST, request.FILES)
if p_form.is_valid():
p_form.save()
return redirect('profile')
else:
p_form = UpdateProfile()
context = {
'p_form': p_form
}
return render(request,'profile.html',context)
urls.py网址.py
urlpatterns = [
path('', views.index, name='index'),
path('home', views.index, name='home'),
path('signup', views.signup, name='signup'),
path('postskill', views.postskill, name='postskill'),
path('profile', views.profile, name='profile'),
]
template of profile.html配置文件模板.html
<img class="rounded-circle account-img" src="{{user.profile.image.url}}" height="100" width="100">
<h5> First Name: {{user.first_name}} </h5>
<h5> Last Name: {{user.last_name}} </h5>
<h5> Username: {{user.username}} </h5>
<h5> Email: {{user.email}} </h5>
<p> Bio: {{user.profile.bio}} </p>
<button class="btn btn-primary" onClick="myFunction()"> UpdateProfile</button>
<div id ="hide">
{% csrf_token %}
<form method = "POST" enctype="multipart/form-data">
{% csrf_token %}
{{ p_form|crispy }}
<button class="btn btn-outline-info" type="submit">Update </button>
</form>
</div>
{% endblock %}
And when i press the update button in browser.当我在浏览器中按下更新按钮时。 Error shown:
显示错误:
IntegrityError at /profile
NOT NULL constraint failed: tutorapp_profile.user_id
Request Method: POST
Request URL: http://127.0.0.1:8000/profile
Django Version: 3.0.3
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: tutorapp_profile.user_id
Exception Location: /home/arpan/anaconda3/envs/MyDjangoEnv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 396
Python Executable: /home/arpan/anaconda3/envs/MyDjangoEnv/bin/python
Python Version: 3.8.5
You need to fill in the user
field if that profile.如果该配置文件,您需要填写
user
字段。 If you want to link it to the logged user, you can work with:如果要将其链接到已登录的用户,可以使用:
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
if request.method == 'POST':
p_form = UpdateProfile(request.POST, request.FILES)
if p_form.is_valid():
p_form
.instance.user = request.user
p_form.save()
return redirect('profile')
else:
p_form = UpdateProfile()
context = {
'p_form': p_form
}
return render(request,'profile.html',context)
or in case you want to update the (already existing) profile
of the logged in user:或者如果您想更新登录用户的(已经存在的)
profile
:
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
if request.method == 'POST':
p_form = UpdateProfile(request.POST, request.FILES
, instance=request.user.profile)
if p_form.is_valid():
p_form.save()
return redirect('profile')
else:
p_form = UpdateProfile()
context = {
'p_form': p_form
}
return render(request,'profile.html',context)
Note : It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly.注意:通常使用
settings.AUTH_USER_MODEL
[Django-doc]引用用户 model 比直接使用User
model [Django-doc] 更好。 For more information you can see the referencing theUser
model section of the documentation .有关更多信息,您可以查看参考文档的
User
model部分。
Note : You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc] .注意:您可以使用
@login_required
装饰器 [Django-doc]将视图限制为经过身份验证的用户的视图。
Note : Usually a
Form
or aModelForm
ends with a…Form
suffix, to avoid collisions with the name of the model, and to make it clear that we are working with a form .注意:通常
Form
或ModelForm
以…Form
后缀结尾,以避免与 model 的名称冲突,并明确我们正在使用form 。 Therefore it might be better to useUpdateProfileForm
instead of.UpdateProfile
因此,使用
UpdateProfileForm
而不是可能会更好。UpdateProfile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.