Я получил ошибку "Поле 'id' ожидало число, но получило 'h'." при отправке формы с видео url (много к одному) в Django

Я новичок в кодировании на Python и использую Django, и у меня возникли проблемы в моем проекте при отправке формы, включающей url видео, я получаю эту ошибку :

"ValueError at /edit_account_details/5/
Field 'id' expected a number but got 'h'.
Request Method: POST
Request URL:    http://127.0.0.1:8000/edit_account_details/5/
Django Version: 4.2.10
Exception Type: ValueError
Exception Value:    
Field 'id' expected a number but got 'h'.
Exception Location: C:\.\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py, line 2055, in get_prep_value
Raised during:  core.views.edit_profile
Python Executable:  C:\.\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.13
Python Path:    
['C:\\...\\Dessoc\\dessoc',
 'C:\\.\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\.\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\.\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\.\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\.\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time:    Wed, 13 Mar 2024 21:28:03 +0000"

если я оставляю поле url пустым, оно работает идеально,

Мой код для model таков:

class Account(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    date_of_deceased = models.DateField()
    rest_location_coordinates = models.CharField(max_length=255)
    rest_location_info = models.TextField(blank=True)
    biography = models.TextField(blank=True)
    photo_gallery = models.ManyToManyField('Photo')
    video_gallery = models.ManyToManyField('Video')
    guestbook_entries = models.ManyToManyField(GuestbookEntry, blank=True, related_name='account_guestbook_entries')


    def __str__(self):
        return f"{self.first_name} {self.last_name} - {self.profile.user.username}"
    
class Photo(models.Model):
    account_id = models.ForeignKey(Account, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to='photos/')

    def __str__(self):
        return self.title

class Video(models.Model):
    account_id = models.ForeignKey(Account, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    video_url = models.URLField()

    def __str__(self):
        return self.title

    def save_form_data(self, instance, data):
        if data is None:
            return
        # Check if 'video_url' is present in data; if not, do nothing
        if 'video_url' in data:
            video_url = data['video_url']
            # Transform YouTube links to embed links
            if 'youtube.com/watch?v=' in video_url:
                video_id = video_url.split('v=')[1]
                embed_url = f'https://www.youtube.com/embed/{video_id}'
                data['video_url'] = embed_url
        default_title = f"Video Title ({data['video_url']})"
        # Use the default title if 'title' is not provided in the form data
        data['title'] = data.get('title', default_title)
        super(Video, self).save_form_data(instance, data)

Мой код для forms таков:

class AccountForm(forms.ModelForm):
    class Meta:
        model = Account
        fields = ['first_name', 'last_name', 'date_of_deceased',
                  'rest_location_coordinates', 'rest_location_info', 'biography'
                  #,'photo_gallery'
                  , 'video_gallery'
                  ]
        
        widgets = {
            'date_of_deceased': forms.DateInput(attrs={'type': 'date'}),
        }
    #photo_gallery = forms.ImageField(required=False)
    video_gallery = forms.CharField(required=False, label='YouTube Video Link')

, а код в views выглядит так:

@login_required(login_url='signin')
def edit_profile(request, account_id):
     # Retrieve the Account for editing
    x = Account.objects.get(id = account_id)
    print (x)
    account = get_object_or_404(Account, pk=account_id)   
    print (account)
    if request.method == 'POST':                       
        form = AccountForm(request.POST, request.FILES, instance=account)        
        if form.is_valid():            
            form.save()           
            return redirect('account_details', account_id=account.id)
        else:
            print("Form is not valid:", form.errors)
    else:
        form = AccountForm(instance=account)   

    return render(request, 'edit_profile.html', {'form': form, 'profile': account.profile})
    #return render(request, 'edit_profile.html', {'form': form})
    # Your implementation for editing a profile goes here

Пришлось отключить и "Фото", так как оно тоже выдает ошибки

Я печатаю Ids для видео через консоль, и это выглядит правильно

Вернуться на верх