Не удается обновить данные в Django Form

Я не могу загрузить данные в Профиль. Как решить эту проблему?

models.py:

class Profile(models.Model):
    user        = models.OneToOneField(User,on_delete=models.CASCADE, blank=True, null=True)
    name        = models.CharField(max_length=200, null=True)
    email       = models.CharField(max_length=200, null=True)
    created_at  = models.DateField(auto_now_add=True)
    alamat      = models.CharField(max_length=200, null=True)
    no_tlp      = models.IntegerField(default=0)
    wilayah     = models.CharField(max_length=200, null=True) 
    j_kel       = models.CharField(max_length=200, null=True)
    pic_Profile = models.ImageField(upload_to='profil/',default="person-circle.svg",null=True, blank=True)
    def __str__(self):
        return str(self.id)

forms.py:

class Uplaoddata(ModelForm):
        no_tlp = forms.CharField(label='No Telpon', max_length=100)
        wilayah = forms.ChoiceField(label =("Wilayah"),widget=forms.Select, choices=wilayah ,help_text="<style>.errorlist{display:None} </style>")
        j_kel = forms.ChoiceField(label = ("Jenis Kelamin"),widget=forms.Select, choices=Jenis ,help_text="<style>.errorlist{display:None} </style>")
        pic_Profile = forms.ImageField(label='Foto Profil', max_length=100)
        class Meta:
            model=Profile
            fields=["email", "name", "alamat", "no_tlp", "wilayah", "j_kel", "pic_Profile"]

views.py:

def home(request):
    data = cartData(request)
    cartItems       = data['cartItems'] 
    id_profil       = request.user.profile
    profiles        = Profile.objects.get(id__contains=id_profil)
    if request.method == "POST":
        form = Uplaoddata(request.POST ,request.FILES, instance=profiles)
        if form.is_valid():
            form.save()
    else:
        form=Uplaoddata(instance=profiles)
        print("Data Tidak terupdate")
    context = {'profiles':profiles,'form':form, 'cartItems':cartItems}
    return render(request, 'home.html',context)

Ок, вероятно, вам следует удалить instance=profiles внутри оператора if.

def home(request):
    data = cartData(request)
    cartItems       = data['cartItems'] 
    id_profil       = request.user.profile
    profiles        = Profile.objects.get(id__contains=id_profil)
    if request.method == "POST":
        form = Uplaoddata(request.POST ,request.FILES)
        if form.is_valid():
            form.save()
    else:
        form=Uplaoddata(instance=profiles)
        print("Data Tidak terupdate")
    context = {'profiles':profiles,'form':form, 'cartItems':cartItems}
    return render(request, 'home.html',context)
Вернуться на верх