/profile NOT NULL约束处的IntegrityError失败:tutorapp_profile.user_id

2024-10-17 06:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个应用程序,用于查找导师,导师需要登录并在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

Tags: pathnamepyselfformmodelsrequestprofile
1条回答
网友
1楼 · 发布于 2024-10-17 06:24:16

如果需要配置文件,则需要填写user字段。如果要将其链接到已登录的用户,可以使用:

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)

或者,如果要更新登录用户的(已存在)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 the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].


Note: Usually a Form or a ModelForm 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. Therefore it might be better to use UpdateProfileForm instead of UpdateProfile.

相关问题 更多 >