# -*- coding: utf-8 -*-
'''
Created on Nov 14, 2012
@author: ymh
'''
from . import settings
from .models import VideoKCRel
from .utils import get_all_objects
from django import forms
import logging
import requests
logger = logging.getLogger(__name__)
class VideoKCRelForm(forms.ModelForm):
iri_id = forms.CharField(max_length=255, widget=forms.widgets.Select())
project_id = forms.CharField(max_length=255, widget=forms.widgets.Select())
def __init__(self, *args, **kwargs):
super(VideoKCRelForm, self).__init__(*args, **kwargs)
url = settings.LDT_API_URL + "contents/"
contents = get_all_objects(url, {'limit':settings.LDT_MAX_FETCH}, 'front_project')
#remove contents that already are associated
associated_rel = dict([(rel.iri_id, rel) for rel in VideoKCRel.objects.all()])
self.fields['iri_id'].widget.choices = [(content['iri_id'], content['title']) for content in contents if (content['iri_id'] not in associated_rel) or (content['iri_id'] == self['iri_id'].value())]
url = settings.LDT_API_URL + "projects/"
projects = get_all_objects(url, {'state': 2, 'limit': settings.LDT_MAX_FETCH}, None)
values = [(None, "-----")]
values.extend([(project['ldt_id'], project['title']) for project in projects])
self.fields['project_id'].widget.choices = values
self.fields['content_title'].widget.attrs['readonly'] = True
def clean_content_title(self):
iri_id = self.cleaned_data['iri_id']
url = settings.LDT_API_URL + "contents/%s/" % iri_id
r = requests.get(url)
if r.status_code != requests.codes.ok: #@UndefinedVariable
logger.error("Error when requesting contents " + repr(r.status_code) + " : " + repr(r.text))
raise forms.ValidationError("Unable to request content %s" % url)
return r.json.get('title', None)
class Meta:
model = VideoKCRel