Ahmad Ajmi
Ahmad Ajmi

Reputation: 7271

Django -- form validation

I have a model that can access Api and return json data

class Video(models.Model):
   url = models.URLField(_('URL'), blank=True)
   type = models.CharField(max_length=10, null=True, blank=True)

   def get_oembed_info(self, url):
      api_url = 'http://api.embed.ly/1/oembed?'
      params = {'url': url, 'format': 'json'}
      fetch_url =  'http://api.embed.ly/1/oembed?%s' % urllib.urlencode(params)
      result = urllib.urlopen(fetch_url).read()
      result = json.loads(result)
      return result

  def get_video_info(self):
     url = self.url
     result = self.get_oembed_info(url)
     KEYS = ('type', 'title', 'description', 'author_name')
     for key in KEYS:
       if result.has_key(key):
          setattr(self, key, result[key])

  def save(self, *args, **kwargs):
     if not self.pk:
        self.get_video_info()

     super(Video, self).save(*args, **kwargs)

class VideoForm(forms.ModelForm):
  def clean(self):
    if not self.cleaned_data['url'] and not self.cleaned_data['slide_url']:
      raise forms.ValidationError('Please provide either a video url or a slide url')
    return self.cleaned_data

I want to access the type field while submitting the form, so if the type is other than "something" raise an Error like in the above clean method. Or how can I access get_oembed_info method result in VideoForm Class.

Solution

Well as Thomas said to call the model's clean method and then do the magic

def clean(self):
   self.get_video_info()
   if self.type == 'something':
      raise ValidationError("Message")

Upvotes: 0

Views: 116

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55199

A ModelForm is going to going to call your model's clean method during its validation process. That method can raise ValidationError's which will be added to your form's errors.

You could therefore implement your validation logic in your model's clean method, where the get_oembed_info method is available using self.get_oembed_info().

Upvotes: 3

Related Questions