src/hp/forms.py
author ymh <ymh.work@gmail.com>
Wed, 28 Nov 2012 02:12:51 +0100
changeset 95 c63f2508c34d
parent 91 eb2aa2a469e2
permissions -rw-r--r--
improve on kc rel form to avoid having all the contents in the drop down list, only those available.

# -*- 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