src/hp/forms.py
author ymh <ymh.work@gmail.com>
Tue, 27 Nov 2012 01:48:15 +0100
changeset 91 eb2aa2a469e2
parent 83 07c9aa7de765
child 95 c63f2508c34d
permissions -rw-r--r--
add content title to relations

# -*- 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')
        self.fields['iri_id'].widget.choices = [(content['iri_id'], content['title']) for content in contents]
        
        url = settings.LDT_API_URL + "projects/"
        projects = get_all_objects(url, {'state': 2, 'limit': settings.LDT_MAX_FETCH}, None)
        logger.debug("projects " + repr(projects))
        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