简体   繁体   中英

FOREIGN KEY constraint failed in django

This is my models.py

from ast import Delete
from email.policy import default
from django.db import models
from django.contrib.auth.models import User


class Euser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=10,null=True)
    birthdate = models.DateField(null=True,)
    profile_pic = models.ImageField(null=True, )
    cover_pic = models.ImageField( null=True, upload_to="images/%y")

    def __str__(self):
        return self.phone

views.py

def editprofile(request, pk):
    return render(request, 'proedit.html')

def submitedit(request):
    if request.method=="POST":

        current_user = request.user.id
        firstname = request.POST.get('firstname') 
        lastname = request.POST.get('lastname')
        username = request.POST.get('username')
        email = request.POST.get('email')
        phone = request.POST.get('mobileno')
        birthdate = request.POST.get('birthdate')
        profile_pic = request.FILES['profile_pic']

       
        print(current_user)
        User.objects.filter(pk=current_user).update(username=username,first_name=firstname,last_name=lastname,email=email)
      
        Euser.objects.filter(pk=current_user).update_or_create(
        phone=phone,birthdate=birthdate,profile_pic=profile_pic,
        defaults={'phone': phone,'birthdate': birthdate,'profile_pic': profile_pic},)

I am trying to update the data from web request. i haven't used forms.py. Do i have to change something?

You should not search related object with pk of other object. Change this:

Euser.objects.filter(pk=current_user)

To that:

Euser.objects.filter(user=current_user)

Your function wanted to create new Euser , but you didn't provide User nor its id to the creation process. Add user=current_user to update_or_create :

Euser.objects.filter(pk=current_user).update_or_create(
    phone=phone, birthdate=birthdate, profile_pic=profile_pic, user=current_user,
    defaults={'phone': phone, 'birthdate': birthdate, 'profile_pic': profile_pic},
)

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