I am using the YouTube Data API to create an object, but when I create a single object, it creates two objects - one with the proper details and one that is blank. How can I resolve this issue?
I am trying with the following code.view.py
class VideoCreateView(CreateView): model = Video form_class = VideoForm template_name = "videos/video_form.html" def form_valid(self, form): video = Video() video.url = form.cleaned_data['url'] parse = urllib.parse.urlparse(video.url) video_id = urllib.parse.parse_qs(parse.query).get('v') if video_id: video.youtube_id =video_id[0] response = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={video_id[0]}&key={YOUTUBE_API_KEY}') json = response.json() items = json["items"] assert len(items) <= 1 if len(items): title = items[0]["snippet"]["title"] video.title = title video.save() else: title = "N/A" return super().form_valid(form)
models.py
class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) slug = models.SlugField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("videos:video_detail", kwargs={"slug":self.slug})def video_pre_save_reciever(sender,instance,*args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance)pre_save.connect(video_pre_save_reciever,Video)
if more code is require than tell me in comment , i will update my question with that information.