简体   繁体   中英

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. 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

Here is my model of Profile in 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'

and its model form

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

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

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


<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. 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
            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:

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.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM