我正在制作一个应用程序,用于查找导师,导师需要登录并在web应用程序中发布他们的工作。在为导师开发个人资料部分时,我无法添加更新或上传新个人资料和个人资料图片的功能。我是django的新手
这是我在models.py中的个人资料模型
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'
及其模型形式
class UpdateProfile(forms.ModelForm):
class Meta:
model = Profile
fields =['image','bio',]
def clean(self):
super(UpdateProfile, self).clean()
return self.cleaned_data
纵断面图视图.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)
url.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'),
]
profile.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 %}
当我按下浏览器中的“更新”按钮时。错误显示:
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
如果需要配置文件,则需要填写
user
字段。如果要将其链接到已登录的用户,可以使用:或者,如果要更新登录用户的(已存在)
profile
,请执行以下操作:相关问题 更多 >
编程相关推荐