コード例 #1
0
ファイル: forms.py プロジェクト: moshthepitt/answers
def make_quiz_form(quiz, select_to_radio=False):
    """
    Generates a form on the fly based on the Quiz questions
    """
    form_fields = OrderedDict()
    for question in quiz.get_questions():
        AnswerModel = question.get_answer_class()
        model_fields = fields_for_model(AnswerModel, exclude=['userprofile', 'review'])
        if AnswerModel == MultipleChoiceAnswer or AnswerModel == RatingAnswer:
            if select_to_radio or (quiz.question_widget == quiz.RADIO_WIDGET) or (question.widget == question.RADIO_WIDGET):
                model_fields = fields_for_model(
                    AnswerModel, exclude=['userprofile', 'review'], formfield_callback=multiplechoice_to_radio)
                # Begin Diry hack
                # for when radio select has for some reason not been set by fields_for_model
                # this happens for RatingAnswer objects
                # first we check if choices exist to avoid none choice fields
                if hasattr(model_fields['answer'], '_choices'):
                    # then we check if the widget is still Select
                    if isinstance(model_fields['answer'].widget, Select):
                        # we manually make it into a Radio Select field
                        model_fields['answer'].widget = RadioSelect()
                        # we remove the empty answer choice usually preset in Select Fields
                        if not model_fields['answer']._choices[0][0]:
                            model_fields['answer']._choices.pop(0)
                # End Diry hack

        answer_field = model_fields['answer']
        answer_field.required = question.required
        # answer_field.question = question ?? should this be included
        answer_field.has_image_answers = question.has_image_answers
        answer_field.widget_to_use = question.widget
        other_field = None
        if question.image:
            thumb_size = getattr(settings, 'QUESTION_LABEL_THUMBS_SIZE', "500x400")
            thumb = get_thumbnail(question.image.file, thumb_size)
            answer_field.label = format_html(
                "<img src='{thumb}' class='img-responsive question-label' alt='{qtitle}' title='{qtitle}' /><span class='question-text-latel'>{qtitle}</span>", thumb=thumb.url, qtitle=smart_str(question.title))
            if quiz.show_question_numbers:
                answer_field.label = format_html(
                    "<img src='{thumb}' class='img-responsive question-label' alt='{qtitle}' title='{qtitle}' /><span class='question-text-latel'>{qtitle}</span>", thumb=thumb.url, qtitle=smart_str("{}. {}".format(question.order, question.title)))
        else:
            this_label = question.title
            if quiz.show_question_numbers:
                this_label = "{}. {}".format(question.order, this_label)
            if question.description:
                answer_field.label = format_html("<span class='question-text-latel'>{}</span><div class='question-description'>{}</div>", smart_str(
                    this_label), mark_safe(smart_str(question.description).replace('\n', '<br />')))
            else:
                answer_field.label = smart_str(this_label)
        if question._meta.model == MultipleChoiceQuestion:
            answer_field.queryset = MultipleChoiceOption.objects.filter(question=question)
            if answer_field.queryset.filter(other=True).exists():
                other_field = CharField()
                other_field.widget.attrs['class'] = "other-field id_answer_{}".format(question.id)
                other_field.label = _("If you selected Other, please specify what you meant")
                other_field.required = False
        form_fields['answer_{}'.format(question.id)] = answer_field
        if other_field:
            form_fields['other_{}'.format(question.id)] = other_field
    return type('QuizForm', (BaseForm,), {'base_fields': form_fields})
コード例 #2
0
    def __init__(self, instance=None, *args, **kwargs):
        super(LocalizacaoUpdateForm, self).__init__(instance=instance, *args, **kwargs)
        # Retrieve the fields from Endereco and Coordenada model and update the fields with it
        self.fields.update(fields_for_model(Endereco))
        self.fields.update(fields_for_model(Coordenada))

        for field in self.fields:
            self.fields[field].widget.attrs.update({'class': 'form-control',})
            self.fields[field].error_messages={'required': 'Este campo é obrigatório'}
コード例 #3
0
ファイル: forms.py プロジェクト: stefanfoulis/project-nani
    def __new__(cls, name, bases, attrs):
        super_new = super(TranslateableModelFormMetaclass, cls).__new__

        formfield_callback = attrs.pop("formfield_callback", None)
        declared_fields = get_declared_fields(bases, attrs, False)
        new_class = super_new(cls, name, bases, attrs)

        if "media" not in attrs:
            new_class.media = media_property(new_class)
        opts = new_class._meta = ModelFormOptions(getattr(new_class, "Meta", attrs.get("Meta", None)))
        if opts.model:
            if not issubclass(opts.model, TranslateableModel):
                raise Exception("Only TranslateableModel subclasses may use TranslateableModelForm")
            mopts = opts.model._meta

            shared_fields = mopts.get_all_field_names()

            sfieldnames = [field for field in opts.fields or [] if field in shared_fields]
            tfieldnames = [field for field in opts.fields or [] if field not in shared_fields]
            sexclude = [field for field in opts.exclude or [] if field in shared_fields]
            texclude = [field for field in opts.exclude or [] if field not in shared_fields]

            if not sfieldnames:
                sfieldnames = None
            if not tfieldnames:
                tfieldnames = None

            # If a model is defined, extract form fields from it.
            sfields = fields_for_model(opts.model, sfieldnames, sexclude, opts.widgets, formfield_callback)
            tfields = fields_for_model(
                mopts.translations_model, tfieldnames, texclude, opts.widgets, formfield_callback
            )

            fields = sfields
            fields.update(tfields)

            # make sure opts.fields doesn't specify an invalid field
            none_model_fields = [k for k, v in fields.iteritems() if not v]
            missing_fields = set(none_model_fields) - set(declared_fields.keys())
            if missing_fields:
                message = "Unknown field(s) (%s) specified for %s"
                message = message % (", ".join(missing_fields), opts.model.__name__)
                raise FieldError(message)
            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields
        new_class.declared_fields = declared_fields
        new_class.base_fields = fields
        return new_class
コード例 #4
0
 def set_value_field(self, model, field_name):
     """
     Adds a ``value`` field to this form that uses the appropriate formfield for the named target
     field.  This will help to ensure that the value is correctly validated.
     """
     fields = fields_for_model(model, fields=[field_name])
     self.fields['value'] = fields[field_name]
コード例 #5
0
ファイル: admin.py プロジェクト: anton98z/jadro
 def get_readonly_fields(self, request, obj=None):
     fields = set(super(ReadOnlyAdmin,self).get_readonly_fields(request, obj))
     if self.declared_fieldsets:
         fields.update(flatten_fieldsets(self.declared_fieldsets))
     else:
         fields.update(fields_for_model(self.model).keys())
     return list(fields)
コード例 #6
0
    def handle(self, *fixture_labels, **options):

        if len(fixture_labels) > 0:
            path = fixture_labels[0]
            if not os.path.exists(path):
                print "Path does not exist:", path
                return

            fields = fields_for_model(Category)

            reader = csv.reader(open(path), delimiter=";")
            self.header = reader.next()
            columns = list(set(fields.keys()) & set(self.header))
            if "id" in self.header:
                key = "id"
            elif "slug" in self.header:
                key = "slug"
            else:
                raise ValueError("Either id or slug column must be present in csv data.")

            for row in reader:
                pk = self.get_value(key, row)
                q = {key: pk}
                data = dict([(c, getattr(self, "resolve_" + c, self.get_value)(c, row)) for c in columns])
                cat = None
                if Category.objects.filter(**q).count() > 0:
                    Category.objects.filter(**q).update(**data)
                    cat = Category.objects.get(**q)
                else:
                    if key not in data:
                        data[key] = pk
                    cat = Category(**data)

                if cat:
                    cat.save()
コード例 #7
0
    def handle(self, *fixture_labels, **options):

        if len(fixture_labels) > 0:
            path = fixture_labels[0]
            if not os.path.exists(path):
                print "Path does not exist:", path
                return

            fields = fields_for_model(Product)
            print "fields:", fields.keys()
            reader = csv.reader(open(path), delimiter=";")
            self.header = reader.next()
            print "header", self.header
            columns = list(set(fields.keys()) & set(self.header))
            print "columns:", columns
            for row in reader:
                id = self.get_value("id", row)
                data = dict([(c, getattr(self, "resolve_" + c, self.get_value)(c, row)) for c in columns])
                prod = None
                try:
                    prod = Product.objects.get(id=id)
                except Product.DoesNotExist:
                    data["id"] = id
                    pl = Placeholder(slot="product_description")
                    pl.save()
                    data["description"] = pl
                    prod = Product(**data)
                else:
                    Product.objects.filter(id=id).update(**data)
                    prod = Product.objects.get(id=id)

                if prod:
                    prod.save()
                    self.post_create(prod, row)
コード例 #8
0
    def __new__(cls, name, bases, attrs):
        formfield_callback = attrs.pop("formfield_callback", None)
        try:
            parents = [b for b in bases if issubclass(b, ModelForm)]
        except NameError:
            # We are defining ModelForm itself.
            parents = None
        declared_fields = get_declared_fields(bases, attrs, False)
        new_class = super(CachedModelFormMetaclass, cls).__new__(cls, name, bases, attrs)
        if not parents:
            return new_class

        if "media" not in attrs:
            new_class.media = media_property(new_class)
        opts = new_class._meta = CachedModelFormOptions(getattr(new_class, "Meta", None))
        if opts.objects:
            formfield_callback = make_formfield_callback(formfield_callback, opts.objects)
        if opts.model:
            # If a model is defined, extract form fields from it.
            fields = fields_for_model(opts.model, opts.fields, opts.exclude, opts.widgets, formfield_callback)
            # make sure opts.fields doesn't specify an invalid field
            none_model_fields = [k for k, v in list(fields.items()) if not v]
            missing_fields = set(none_model_fields) - set(declared_fields.keys())
            if missing_fields:
                message = "Unknown field(s) (%s) specified for %s"
                message = message % (", ".join(missing_fields), opts.model.__name__)
                raise FieldError(message)
            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields
        new_class.declared_fields = declared_fields
        new_class.base_fields = fields
        return new_class
コード例 #9
0
ファイル: admin.py プロジェクト: wx-ast/django-seo
def get_model_form(metadata_class):
    model_class = metadata_class._meta.get_model('model')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)
    content_type_choices = [(x._get_pk_val(), smart_unicode(x)) for x in ContentType.objects.filter(id__in=content_types)]

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + core_choice_fields(metadata_class)
    _fields = important_fields + fields_for_model(model_class, exclude=important_fields).keys()

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ChoiceField(label=capfirst(_("model")), choices=content_type_choices)

        class Meta:
            model = model_class
            fields = _fields

        def clean__content_type(self):
            value = self.cleaned_data['_content_type']
            try:
                return ContentType.objects.get(pk=int(value))
            except (ContentType.DoesNotExist, ValueError):
                raise forms.ValidationError("Invalid ContentType")

    return ModelMetadataForm
コード例 #10
0
    def fields(cls):
        widget_fields = [
            f.name for f in Widget._meta.fields]

        return fields_for_model(
            cls, exclude=widget_fields,
            widgets=WIDGETS)
コード例 #11
0
    def __new__(cls, name, bases, attrs):
        """
        Declares multilingual fields before constructor of model form is called.
        """
        if 'Meta' in attrs:
            meta = attrs.get('Meta')
            if getattr(meta, 'model', None):
                translation_model = getattr(meta.model._meta, 'translation_model', None)
                if translation_model:
                    # Exclude translation base fields
                    exclude = getattr(meta, 'exclude', None)
                    if exclude is None:
                        exclude = ('id', 'language_code', 'master')
                    else:
                        exclude = list(exclude) + ['id', 'language_code', 'master']
                    fields = getattr(meta, 'fields', None)
                    widgets = getattr(meta, 'widgets', None)
                    formfield_callback = attrs.get('formfield_callback', None)

                    if fields == ALL_FIELDS:
                        # sentinel for fields_for_model to indicate "get the list of
                        # fields from the model"
                        fields = None

                    model_fields = fields_for_model(translation_model, fields, exclude, widgets, formfield_callback)
                    for field_name, field in model_fields.items():
                        # Exclude untranslated fields
                        if field is not None:
                            attrs.setdefault(field_name, field)
        return super(MultilingualModelFormMetaclass, cls).__new__(cls, name, bases, attrs)
コード例 #12
0
ファイル: forms.py プロジェクト: brajeshvit/virtual
    def __new__(cls, name, bases, attrs):
        # Force presence of meta class, we need it
        meta = attrs.get('Meta')
        if meta is None:
            meta = attrs['Meta'] = type('Meta', (object,), {})

        model = getattr(meta, 'model', None)
        fields = getattr(meta, 'fields', None)

        # Force exclusion of language_code as we use cleaned_data['language_code']
        exclude = meta.exclude = list(getattr(meta, 'exclude', ()))
        if fields is not None and 'language_code' in fields:
            raise FieldError('Field \'language_code\' is invalid.')

        # If a model is provided, handle translatable fields
        if model:
            if not issubclass(model, TranslatableModel):
                raise TypeError('TranslatableModelForm only works with TranslatableModel'
                                ' subclasses, which %s is not.' % model.__name__)

            # Additional exclusions
            exclude.append(model._meta.translations_accessor)
            if fields is not None and model._meta.translations_accessor in fields:
                raise FieldError('Field \'%s\' is invalid', model._meta.translations_accessor)

            # Get translatable fields
            tfields = fields_for_model(
                model._meta.translations_model,
                fields=fields,
                exclude=exclude + list(veto_fields),
                widgets=getattr(meta, 'widgets', None),
                formfield_callback=attrs.get('formfield_callback')
            )

            # Drop translatable fields from Meta.fields
            if fields is not None:
                meta.fields = [field for field in fields if tfields.get(field) is None]

        # Create the form class
        new_class = super(TranslatableModelFormMetaclass, cls).__new__(cls, name, bases, attrs)

        # Add translated fields into the form's base fields
        if model:
            if fields is None:
                # loop, as Django's variant of OrderedDict cannot consume generators
                for name, field in tfields.items():
                    if field is not None:
                        new_class.base_fields[name] = field
            else:
                # rebuild the fields to respect Meta.fields ordering
                new_class.base_fields = OrderedDict(
                    item for item in (
                        (name, new_class.base_fields.get(name, tfields.get(name)))
                        for name in fields
                    )
                    if item[1] is not None
                )
                # restore hijacked Meta.fields
                new_class._meta.fields = meta.fields = fields
        return new_class
コード例 #13
0
ファイル: edit_handlers.py プロジェクト: Parbhat/wagtail
def extract_panel_definitions_from_model_class(model, exclude=None):
    if hasattr(model, 'panels'):
        panels = model.panels

        if exclude is not None:
            # Filter out fields in exclude
            panels = [
                panel for panel in panels
                if isinstance(panel, FieldPanel) and panel.field_name not in exclude
            ]

        return panels

    panels = []

    _exclude = []
    if exclude:
        _exclude.extend(exclude)

    fields = fields_for_model(model, exclude=_exclude, formfield_callback=formfield_for_dbfield)

    for field_name, field in fields.items():
        try:
            panel_class = field.widget.get_panel()
        except AttributeError:
            panel_class = FieldPanel

        panel = panel_class(field_name)
        panels.append(panel)

    return panels
コード例 #14
0
ファイル: admin.py プロジェクト: entvia/django-seo
def get_modelinstance_form(metadata_class):
    model_class = metadata_class._meta.get_model('modelinstance')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + ['_object_id'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ModelChoiceField(
            queryset=ContentType.objects.filter(id__in=content_types),
            empty_label=None,
            label=capfirst(_("model")),
        )

        _object_id = forms.IntegerField(label=capfirst(_("ID")))

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm
コード例 #15
0
    def prepare_value(self, value):

        #Value is not None when we open the form in edit mode or when there is a validation error.
        #If value is not none we have to insert the initial value for each embedded field
        if value is not None:
            #it can be a json unicode string of the object or the object itself
            if isinstance(value,unicode):
                fields_value_as_dict = json.loads(value)
                fields = copy.deepcopy(self.embedded_fields)
                for (k,v) in fields.iteritems():
                    v.initial = fields_value_as_dict[k]

            elif isinstance(value, dict): #This case handles the ListEmbeddedModelFormField caller
                fields_value_as_dict = value
                fields = copy.deepcopy(self.embedded_fields)
                for (k,v) in fields.iteritems():
                    v.initial = fields_value_as_dict[k]

            else:
                fields= fields_for_model(value)
                for (k,v) in fields.iteritems():
                    v.initial = getattr(value,k)

            return fields

        else:
            #We have to do a deepcopy because embedded_fields is a dict whose values are Field references.
            return copy.deepcopy(self.embedded_fields)
コード例 #16
0
    def __new__(cls, name, bases, attrs):
        formfield_callback = attrs.pop('formfield_callback', None)
        try:
            # HACK: Had to replace baseclass
            # TODO: Report that this can not overrode, there should be something else.
            parents = [b for b in bases if issubclass(b, MultilingualModelForm)]
        except NameError:
            # We are defining ModelForm itself.
            parents = None
        declared_fields = get_declared_fields(bases, attrs, False)
        new_class = super(MultilingualModelFormMetaclass, cls).__new__(cls, name, bases,
                attrs)
        if not parents:
            return new_class

        if 'media' not in attrs:
            new_class.media = media_property(new_class)
        opts = new_class._meta = ModelFormOptions(getattr(new_class, 'Meta', None))
        if opts.model:
            # If a model is defined, extract form fields from it.
            fields = fields_for_model(opts.model, opts.fields,
                                      opts.exclude, opts.widgets, formfield_callback)
            found_fields = [k for k, v in fields.items() if v is not None]

            #HACK: This is update of original method. I should be able to change it to overrides
            translation_model = getattr(opts.model._meta, 'translation_model', None)
            if translation_model:
                if opts.exclude is None:
                    exclude = ['id', 'language_code', 'master'] + found_fields
                else:
                    exclude = list(opts.exclude) + ['id', 'language_code', 'master'] + found_fields

                translated_fields = fields_for_model(
                    translation_model, opts.fields, exclude, opts.widgets, formfield_callback
                )

                fields.update(translated_fields)

            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields
        new_class.declared_fields = declared_fields
        new_class.base_fields = fields
        return new_class
コード例 #17
0
ファイル: forms.py プロジェクト: Squishymedia/feedingdb
    def __init__(self, initial=None, instance=None, *args, **kwargs):
        _user_initial = model_to_dict(instance.user, self._user_fields) if instance is not None else {}
        initial.update(_user_initial)
        super(UserOwnProfileForm, self).__init__(initial=initial, instance=instance, *args, **kwargs)
        self.fields.update(fields_for_model(User, self._user_fields))

        # reorder fields according to order above
        self.fields = OrderedDict((k, self.fields[k]) for k in self._field_order)
コード例 #18
0
ファイル: views.py プロジェクト: mek4nr/admin_trigger
def get_formfield(request, obj, field):
    e = EventChangeFieldGenerator(request)
    content_type, obj = unparse_value(obj)

    # Get current value (don't process if an event will change before u or after)
    value = getattr(obj, field)
    fields = e.get_field(obj, field)
    t = fields_for_model(content_type.model_class())
    return HttpResponse(t[fields.name].widget.render(fields, value=value))
コード例 #19
0
    def __init__(self, required=True, widget=None, label=None, initial=None,
                 help_text=None, error_messages=None, show_hidden_initial=False,
                 validators=[], localize=False):

        self.embedded_fields = fields_for_model(initial)
        initial=None

        super(EmbeddedModelFormField, self).__init__(required, widget, label, initial,
                 help_text, error_messages, show_hidden_initial,
                 validators, localize)
コード例 #20
0
ファイル: forms.py プロジェクト: odarbelaeze/pcmresearchgroup
 def __init__(self, instance=None, *args, **kwargs):
     self.extra_fields = ('first_name', 'last_name')
     _initial = kwargs.pop('initial')
     _initial.update(
         model_to_dict(instance.user, self.extra_fields) if instance else {}
     )
     super().__init__(initial=_initial, instance=instance, *args, **kwargs)
     _old_fields = self.fields
     self.fields = fields_for_model(User, self.extra_fields)
     self.fields.update(_old_fields)
コード例 #21
0
ファイル: admin.py プロジェクト: oraclebill/dsusa
 def __init__(self, model, admin_site):
     super(WorkingOrderAdmin, self).__init__(model, admin_site)
     fields = fields_for_model(self.model)            
     for fieldname in admin.util.flatten_fieldsets(self.fieldsets):
         fields.pop(fieldname, None) 
     undeclared_fields = (('Design Information', 
                             {'fields': fields.keys() ,
                              'classes': ('collapse',) } ),)        
     self.readonly_fields = admin.util.flatten_fieldsets(undeclared_fields)
     self.fieldsets += undeclared_fields
コード例 #22
0
ファイル: admin.py プロジェクト: fusionbox/django-fusionbox
 def export_csv(self, request, queryset):
     fields = self.csv_fields or self.fields or fields_for_model(self.model).keys()
     response = HttpResponse(mimetype='text/csv')
     response['Content-Disposition'] = ('attachment; filename=%s.csv'
                                        % self.model._meta.db_table)
     writer = UnicodeWriter(response)
     writer.writerow(fields)
     for obj in queryset.all():
         writer.writerow([self.get_csvable_value(obj, field)
                          for field in fields])
     return response
コード例 #23
0
 def __init__(self, *args, **kwargs):
     super(HStoreModelForm, self).__init__(*args, **kwargs)
     # Always override for fields (dynamic fields maybe deleted/included) 
     opts = self._meta
     if opts.model and issubclass(opts.model, HStoreModel):
         # If a model is defined, extract dynamic form fields from it.
         if not opts.exclude:
             opts.exclude = []
         # hide dfields
         opts.exclude.append('_dfields')
         self.fields = fields_for_model(opts.model, opts.fields,
                                           opts.exclude, opts.widgets)
コード例 #24
0
ファイル: forms.py プロジェクト: jorgevtorresr/SIMCOPV
	def __init__(self,instance=None, *args, **kwargs):
		_fields = ('username','first_name','last_name','email')
		_initial = model_to_dict(instance.usuario, _fields) if instance is not None else {}
		super(PersonaModificarForm, self).__init__(initial=_initial,instance=instance,*args,**kwargs)
		self.fields.update(fields_for_model(User,_fields))
		self.fields['username'].widget.attrs.update({'class':'form-control'})
		self.fields['first_name'].widget.attrs.update({'class':'form-control'})
		self.fields['last_name'].widget.attrs.update({'class':'form-control'})
		self.fields['puesto'].widget.attrs.update({'class':'form-control'})
		self.fields['tipo'].widget.attrs.update({'class':'form-control'})
		self.fields['unidad'].widget.attrs.update({'class':'form-control'})
		self.fields['foto'].widget.attrs.update({'class':'form-control'})
		self.fields['email'].widget.attrs.update({'class':'form-control'})
コード例 #25
0
ファイル: admin.py プロジェクト: wx-ast/django-seo
def get_path_form(metadata_class):
    model_class = metadata_class._meta.get_model('path')

    # Get a list of fields, with _view at the start
    important_fields = ['_path'] + core_choice_fields(metadata_class)
    _fields = important_fields + fields_for_model(model_class, exclude=important_fields).keys()

    class ModelMetadataForm(forms.ModelForm):
        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm
コード例 #26
0
ファイル: permissions.py プロジェクト: Mistborn/ijk
 def get_readonly_fields(self, request, obj=None):
     fields = flatten(self.fields) or fields_for_model(self.model)
     sup = super(SpecialPermissionsAdmin, self).get_readonly_fields(
         request, obj)
     allfields = set(fields) | set(sup)
     if self.is_readonly(request):
         fields = allfields
     elif not self.can_change_all(request):
         fields = [f for f in allfields
             if f not in self.get_changeable_fields(request, obj)]
     else:
         fields = sup
     return fields
コード例 #27
0
ファイル: admin.py プロジェクト: glic3rinu/confine-controller
 def get_readonly_fields(self, request, obj=None):
     """ Makes all fields read only if user doesn't have change permissions """
     if not self.has_change_permission(request, obj=obj, view=False):
         if self.has_view_permission(request, obj=obj):
             excluded_fields = ['object_id', 'content_type']
             model_fields = fields_for_model(self.model).keys()
             fields = []
             # more efficient set.union() is not used for preserving order
             for field in model_fields + list(self.readonly_fields):
                 if field not in excluded_fields and field not in fields:
                     fields.append(field)
             return fields
     return self.readonly_fields
コード例 #28
0
ファイル: efield.py プロジェクト: comick/django-efield
    def render(self, context):
        try:
            obj = context
            for token in self.tokens:
                try:
                    obj = obj[token]
                except TypeError:
                    obj = obj[int(token)]
            field_val = self.field_var.resolve(context)
            assert(isinstance(obj, models.Model))
            #if not context['user'].is_authenticated() or context['user'] != obj.get_owner():
            #    return field_val
        except Exception as e:
            return e

        widget = fields_for_model(type(obj), [self.field_name])[self.field_name].widget

        if 'input_classes' in self.options:
            widget.attrs['class'] = self.options['input_classes']

        class PartialForm(ModelForm):
            class Meta:
                model = type(obj)
                fields = [self.field_name]
                widgets = {
                    self.field_name: widget
                }
        
        c = Context({'value': field_val,
                     'model': obj.__class__.__module__ + '.' + obj.__class__.__name__,
                     'object_id': obj.id,
                     'ef_id': str(EfieldNode.ef_id),
                     'name': self.field_name,
                     'form': PartialForm(instance=obj)
        })
        for opt_key, opt_val in self.options.items():
            if opt_key == 'jstrigger':
                c[opt_key] = opt_val
            else:
                pass
                # Opzione sconosciuta, che fare???
        EfieldNode.ef_id += 1
        field_type = obj._meta.get_field_by_name(self.field_name)[0]
        if self.group_key:
            c['group_key'] = self.group_key
        if isinstance(field_type, ImageField):
            t = template.loader.get_template('efield_image.html')
        else:
            t = template.loader.get_template('efield.html')
        return t.render(c)            
コード例 #29
0
ファイル: validation.py プロジェクト: BobPyron/SideBySideDiff
def _check_form_field_exists(cls, model, opts, label, field):
    if hasattr(cls.form, 'base_fields'):
        try:
            cls.form.base_fields[field]
        except KeyError:
            raise ImproperlyConfigured("`%s.%s` refers to field `%s` that "
                "is missing from the form." % (cls.__name__, label, field))
    else:
        fields = fields_for_model(model)
        try:
            fields[field]
        except KeyError:
            raise ImproperlyConfigured("`%s.%s` refers to field `%s` that "
                "is missing from the form." % (cls.__name__, label, field))
コード例 #30
0
ファイル: validation.py プロジェクト: 0924wyr/blog_code
def check_formfield(cls, model, opts, label, field):
    if getattr(cls.form, 'base_fields', None):
        try:
            cls.form.base_fields[field]
        except KeyError:
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                "is missing from the form." % (cls.__name__, label, field))
    else:
        fields = fields_for_model(model)
        try:
            fields[field]
        except KeyError:
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                "is missing from the form." % (cls.__name__, label, field))
コード例 #31
0
def check_formfield(cls, model, opts, label, field):
    if getattr(cls.form, 'base_fields', None):
        try:
            cls.form.base_fields[field]
        except KeyError:
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                                       "is missing from the form." %
                                       (cls.__name__, label, field))
    else:
        fields = fields_for_model(model)
        try:
            fields[field]
        except KeyError:
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                                       "is missing from the form." %
                                       (cls.__name__, label, field))
コード例 #32
0
ファイル: qs_export.py プロジェクト: fanshuai/kubrick
 def get_titles(self):
     """ 获取文件头信息 """
     model = self._qs.model
     fields = OrderedDict(
         ((k, v.label) for k, v in fields_for_model(model).items()))
     if not self._moheaders:  # 设置默认导出字段
         self._moheaders = list(fields.keys())
     self._moheaders = ['PK'] + self._moheaders
     if not self._output_name:
         # noinspection PyProtectedMember
         self._output_name = model._meta.db_table  # 默认文件名为表名
     if self._is_csv:
         titles = list(fields.keys())  # csv 中文 Excel 乱码
     else:
         titles = ('%s(%s)' % (v, k) for k, v in fields.items())
     return tuple(['PK'] + list(titles))
コード例 #33
0
    def __new__(cls, name, bases, attrs):
        fields = [(field_name, attrs.pop(field_name))
                  for field_name, obj in attrs.items()
                  if isinstance(obj, Field)]
        fields.sort(
            lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter))

        # If this class is subclassing another Form, add that Form's fields.
        # Note that we loop over the bases in *reverse*. This is necessary in
        # order to preserve the correct order of fields.
        for base in bases[::-1]:
            if hasattr(base, 'base_fields'):
                fields = base.base_fields.items() + fields

        attrs['base_fields'] = SortedDictFromList(fields)

        # rest of this method is taken from actual django
        # source for ModelFormMetaclass class
        formfield_callback = attrs.pop('formfield_callback',
                                       lambda f: f.formfield())
        try:
            parents = [b for b in bases if issubclass(b, BaseModelForm)]
        except NameError:
            # We are defining ModelForm itself.
            parents = None
        declared_fields = get_declared_fields(bases, attrs, False)
        new_class = super(SmartModelFormMetaclass,
                          cls).__new__(cls, name, bases, attrs)
        if not parents:
            return new_class

        if 'media' not in attrs:
            new_class.media = media_property(new_class)
        opts = new_class._meta = ModelFormOptions(
            getattr(new_class, 'Meta', None))
        if opts.model:
            # If a model is defined, extract form fields from it.
            fields = fields_for_model(opts.model, opts.fields, opts.exclude,
                                      formfield_callback)
            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields
        new_class.declared_fields = declared_fields
        new_class.base_fields = fields
        return new_class
コード例 #34
0
def form_factory(model):
    # TODO: use a cache ??
    mergeform_factory = merge_form_registry.get(model)

    if mergeform_factory is not None:
        base_form_class = mergeform_factory()

        return type(
            'Merge{}Form'.format(model.__name__), (base_form_class, ),
            fields_for_model(
                model,
                formfield_callback=mergefield_factory,
                exclude=[
                    f.name
                    for f in FieldsConfig.get_4_model(model).hidden_fields
                ],
            ))
コード例 #35
0
    def fields_for_model(self, *args, **kwargs):
        '''
        A replacement for django.forms.models.fields_for_model which respects privacy.
        
        Uses django.forms.models.fields_for_model and just removes hidden fields.
        
        This is what we should use in all forms that are going to display models that
        used the PrivacyMixIn.
        '''
        fields = fields_for_model(self._meta.model, *args, **kwargs)

        if hasattr(self, 'hidden') and isinstance(self.hidden, list):
            for f in self.hidden:
                if f in fields:
                    del fields[f]

        return fields
コード例 #36
0
ファイル: views.py プロジェクト: bernd-wechner/CoGs
    def get_object(self, *args, **kwargs):
        '''Fetches the object to edit and augments the standard queryset by passing the model to the view so it can make model based decisions and access model attributes.'''
        log.debug("Getting initial data from an existing object.")

        self.pk = self.kwargs['pk']
        self.model = class_from_string(self, self.kwargs['model'])
        self.obj = get_object_or_404(self.model, pk=self.kwargs['pk'])

        if not hasattr(self, 'fields') or self.fields == None:
            self.fields = '__all__'

        if callable(getattr(self.obj, 'fields_for_model', None)):
            self.fields = self.obj.fields_for_model()
        else:
            self.fields = fields_for_model(self.model)

        return self.obj
コード例 #37
0
 def get_formset(self, request, obj=None, **kwargs):
     """
     Add field `quantity` to the form on the fly, using the same numeric type as `OrderItem.quantity`
     """
     labels = {'quantity': _("Deliver quantity")}
     attrs = models.fields_for_model(obj.items.model, fields=['quantity'], labels=labels)
     # rename to deliver_quantity, since quantity is already used
     attrs['deliver_quantity'] = attrs.pop('quantity')
     if obj.status == 'pick_goods' and obj.unfulfilled_items > 0:
         attrs['deliver_quantity'].widget.attrs.update(style='width: 50px;')
     else:
         attrs['deliver_quantity'].required = False
     form = type(str('OrderItemForm'), (OrderItemForm,), attrs)
     labels = {'canceled': _("Cancel this item")}
     kwargs.update(form=form, labels=labels)
     formset = super(OrderItemInlineDelivery, self).get_formset(request, obj, **kwargs)
     return formset
コード例 #38
0
    def __init__(self, *args, **kwargs):
        self.language_code = kwargs.pop('language_code')
        super(JournalInformationForm, self).__init__(*args, **kwargs)

        # Fetches proper labels for for translatable fields: this is necessary
        # in order to remove language indications from labels (eg. "Team [en]")
        i18n_fields_label = {
            self.get_i18n_field_name(fname): self._meta.model._meta.get_field(fname).verbose_name
            for fname in self.i18n_field_bases}

        # All translatable fields are TextField and will use CKEditor
        i18n_field_widgets = {fname: CKEditorWidget() for fname in self.i18n_field_names}

        # Inserts the translatable fields into the form fields.
        self.fields.update(
            fields_for_model(self.Meta.model, fields=self.i18n_field_names,
                             labels=i18n_fields_label, widgets=i18n_field_widgets))
コード例 #39
0
ファイル: admin.py プロジェクト: modamania/otdohni
def get_view_form(metadata_class):
    model_class = metadata_class._meta.get_model('view')

    # Restrict content type choices to the models set in seo_models
    view_choices = [(key, " ".join(key.split("_"))) for key in get_seo_views(metadata_class)]
    view_choices.insert(0, ("", "---------"))

    # Get a list of fields, with _view at the start
    important_fields = ['_view'] + core_choice_fields(metadata_class)
    _fields = important_fields + fields_for_model(model_class, exclude=important_fields).keys()

    class ModelMetadataForm(forms.ModelForm):
        _view = forms.ChoiceField(label=capfirst(_("view")), choices=view_choices, required=False)

        class Meta:
            model = model_class
            fields = _fields

    return ModelMetadataForm
コード例 #40
0
def country_data_into_shapefile(country=None):
    """ Convert country osm data into shapefile

    :param country_name: Country name
    :type: str
    """
    if country == 'World' or country == 'world':
        country = None
    queryset = filter_locality(
        extent=None,
        country=country).order_by('row')
    country_name = 'World'
    if country:
        country_name = country

    # get field that needs to be saved
    fields = fields_for_model(LocalityOSM).keys()
    insert_to_shapefile(
        LocalityOSMSerializer(queryset, many=True).data, fields, country_name)
コード例 #41
0
ファイル: forms.py プロジェクト: timnyborg/redpot-unchained
class CreditForm(forms.Form):
    submit_label = 'Add credit'
    enrolment = forms.ModelChoiceField(queryset=Enrolment.objects.all())
    account = fields_for_model(Ledger)['account']
    amount = forms.DecimalField(
        widget=PoundInput(),
        help_text='Positive values decrease debt, negative increase debt')
    narrative = forms.CharField()
    type = forms.ModelChoiceField(
        queryset=TransactionType.objects.filter(is_cash=False, is_active=True))

    def __init__(self, invoice: models.Invoice, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Limit the enrolments to those connected with the invoice
        self.fields['enrolment'].queryset = (Enrolment.objects.filter(
            ledger__invoice=invoice).distinct().select_related(
                'module').order_by('-id'))
        # Dropdown options display the module title
        self.fields['enrolment'].label_from_instance = lambda obj: obj.module
コード例 #42
0
def check_formfield(cls, model, opts, label, field):
    if getattr(cls.form, 'base_fields', None):
        try:
            cls.form.base_fields[field]
        except KeyError:
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                                       "is missing from the form." %
                                       (cls.__name__, label, field))
    else:
        get_form_is_overridden = hasattr(
            cls, 'get_form') and cls.get_form != ModelAdmin.get_form
        if not get_form_is_overridden:
            fields = fields_for_model(model)
            try:
                fields[field]
            except KeyError:
                raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                                           "is missing from the form." %
                                           (cls.__name__, label, field))
コード例 #43
0
    def get_object(self, *args, **kwargs):
        '''Fetches the object to edit and augments the standard queryset by passing the model to the view so it can make model based decisions and access model attributes.'''
        self.pk = self.kwargs['pk']
        self.model = class_from_string(self, self.kwargs['model'])
        self.obj = get_object_or_404(self.model, pk=self.kwargs['pk'])

        if not hasattr(self, 'fields') or self.fields == None:
            self.fields = '__all__'

        if callable(getattr(self.obj, 'fields_for_model', None)):
            self.fields = self.obj.fields_for_model()
        else:
            self.fields = fields_for_model(self.model)

        self.success_url = reverse_lazy('view', kwargs=self.kwargs)

        # Communicate the request user to the models (Django doesn't make this easy, need cuser middleware)
        CuserMiddleware.set_user(self.request.user)

        return self.obj
コード例 #44
0
    def __new__(cls, name, bases, attrs):
        formfield_callback = attrs.pop('formfield_callback', None)
        try:
            parents = [b for b in bases if issubclass(b, ModelForm)]
        except NameError:
            # We are defining ModelForm itself.
            parents = None
        declared_fields = get_declared_fields(bases, attrs, False)
        new_class = super(CachedModelFormMetaclass,
                          cls).__new__(cls, name, bases, attrs)
        if not parents:
            return new_class

        if 'media' not in attrs:
            new_class.media = media_property(new_class)
        opts = new_class._meta = CachedModelFormOptions(
            getattr(new_class, 'Meta', None))
        if opts.objects:
            formfield_callback = make_formfield_callback(
                formfield_callback, opts.objects)
        if opts.model:
            # If a model is defined, extract form fields from it.
            fields = fields_for_model(opts.model, opts.fields, opts.exclude,
                                      opts.widgets, formfield_callback)
            # make sure opts.fields doesn't specify an invalid field
            none_model_fields = [k for k, v in list(fields.items()) if not v]
            missing_fields = set(none_model_fields) - set(
                declared_fields.keys())
            if missing_fields:
                message = 'Unknown field(s) (%s) specified for %s'
                message = message % (', '.join(missing_fields),
                                     opts.model.__name__)
                raise FieldError(message)
            # Override default model fields with any custom declared ones
            # (plus, include all the other declared fields).
            fields.update(declared_fields)
        else:
            fields = declared_fields
        new_class.declared_fields = declared_fields
        new_class.base_fields = fields
        return new_class
コード例 #45
0
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        _fields = ('first_name', 'last_name', 'username', 'email', 'is_staff',
                   'is_active')
        kwargs['initial'] = model_to_dict(instance.user, _fields) \
            if instance is not None else None
        super(PartnerForm, self).__init__(*args, **kwargs)

        pfields = copy.copy(self.fields)
        self.fields = fields_for_model(User, _fields)
        for k, v in pfields.items():
            self.fields.update({k: v})

        # limit and better display entities
        choices = [e.to_treed_tuple() for e in Entity.clean_tree(Entity.ZONE)]
        self.fields['upload_location'].choices = choices
        self.fields['validation_location'].choices = choices

        if instance:
            self.fields['username'].widget.attrs['readonly'] = True

        self.instanciated = instance is not None
コード例 #46
0
def extract_panel_definitions_from_model_class(model, exclude=None):
    if hasattr(model, 'panels'):
        return model.panels

    panels = []

    _exclude = []
    if exclude:
        _exclude.extend(exclude)

    fields = fields_for_model(model, exclude=_exclude, formfield_callback=formfield_for_dbfield)

    for field_name, field in fields.items():
        try:
            panel_class = field.widget.get_panel()
        except AttributeError:
            panel_class = FieldPanel

        panel = panel_class(field_name)
        panels.append(panel)

    return panels
コード例 #47
0
 def field_label(cls, field):
     if not hasattr(cls, 'base_fields'):
         '''
         def tran_form_field(field,**kwargs):
             if type(field)==AutoField:
                 defaults = {'form_class': IntegerField}
                 defaults.update(kwargs)
                 return IntegerField.formfield(field,**defaults)
             else:
                 return field.formfield(field,**kwargs)
             #f = lambda x:IntegerField.formfield(x) if type(x)==AutoField else x.formfield()
         '''
         cls.base_fields = fields_for_model(cls.model, cls.fields,
                                            cls.exclude, None, None)
         '''AutoField djangoform并未为其产生formfield'''
         for f in cls.model._meta.fields:
             if type(f) == AutoField:
                 f.label = f.verbose_name
                 cls.base_fields[f.name] = f
     return cls.labels[field] if cls.labels.has_key(field) else (
         unicode(cls.base_fields[field].label if (cls.base_fields.has_key(
             field) and cls.base_fields[field] is not None) else field))
コード例 #48
0
    def __init__(self, instance=None, *args, **kwargs):
        _fields = ('address', 'zipcode', 'city', 'country', 'province_code')
        _initial = model_to_dict(instance.address,
                                 _fields) if instance is not None else {}

        widgets = {
            'zipcode': forms.TextInput(attrs={'class': 'inputXS'}),
            'city': forms.TextInput(attrs={'class': 'inputM'}),
            #'country': CountryField(queryset=Country.objects.all(), empty_label=_('Select a country'), to_field_name='country'),
            'province_code': forms.HiddenInput()
        }
        kwargs['initial'].update(_initial)
        super(ShopForm, self).__init__(instance=instance, *args, **kwargs)
        self.fields.update(fields_for_model(Address, _fields, widgets=widgets))
        self.fields['upc'].widget = forms.TextInput(attrs={'class': 'inputM'})
        self.fields['phone'].widget = forms.TextInput(
            attrs={'class': 'inputS'})
        self.fields['description'].widget = forms.Textarea(attrs={
            "cols": 30,
            "rows": 4
        })
        self.fields['latitude'].widget = forms.HiddenInput()
        self.fields['longitude'].widget = forms.HiddenInput()
        self.fields['mother_brand'].widget = forms.HiddenInput()
        self.fields['opening_hours'] = ScheduleField(required=False)
        self.fields['business_reg_num'].widget = forms.TextInput(
            attrs={'class': 'inputM'})
        self.fields['tax_reg_num'].widget = forms.TextInput(
            attrs={'class': 'inputM'})
        currency_choices = [('', '-' * 9)]
        currency_choices.extend([
            (s, s)
            for s in ProductCurrency.objects.all().values_list('code',
                                                               flat=True)
        ])
        self.fields['default_currency'] = forms.ChoiceField(
            choices=currency_choices,
            label=_('Default currency'),
            required=False)
コード例 #49
0
    def handle(self, *fixture_labels, **options):

        if len(fixture_labels) > 0:
            path = fixture_labels[0]
            if not os.path.exists(path):
                print 'Path does not exist:', path
                return

            fields = fields_for_model(Category)

            reader = csv.reader(open(path), delimiter=";")
            self.header = reader.next()
            columns = list(set(fields.keys()) & set(self.header))
            if 'id' in self.header:
                key = 'id'
            elif 'slug' in self.header:
                key = 'slug'
            else:
                raise ValueError(
                    'Either id or slug column must be present in csv data.')

            for row in reader:
                pk = self.get_value(key, row)
                q = {key: pk}
                data = dict([(c, getattr(self, 'resolve_' + c,
                                         self.get_value)(c, row))
                             for c in columns])
                cat = None
                if Category.objects.filter(**q).count() > 0:
                    Category.objects.filter(**q).update(**data)
                    cat = Category.objects.get(**q)
                else:
                    if key not in data:
                        data[key] = pk
                    cat = Category(**data)

                if cat:
                    cat.save()
コード例 #50
0
 def __init__(self, *args, **kwargs):
     _fields = ('first_name', 'last_name', 'email')
     instance = kwargs.get('instance', None)
     _initial = kwargs.get('initial', {})
     _initial.update(
         model_to_dict(instance.user, _fields
                       ) if instance is not None else {})
     kwargs['initial'] = _initial
     super(BasicProfileForm, self).__init__(*args, **kwargs)
     # reorder fields
     unordered_fields = self.fields
     unordered_fields.update(fields_for_model(User, _fields))
     self.fields = OrderedDict()
     for k in ['first_name', 'last_name', 'email', 'merged_with']:
         try:
             self.fields[k] = unordered_fields.pop(k)
         except Exception:
             # TODO: handle exception
             pass
     # add the fields not listed above at the end
     self.fields.update(unordered_fields)
     for k in ['first_name', 'last_name', 'email']:
         self.fields[k].required = True
コード例 #51
0
ファイル: forms.py プロジェクト: ramon/django-trans
    def __new__(mcs, name, bases, attrs):
        new_class = super(TranslatableFieldsMetaclass, mcs).__new__(mcs, name, bases, attrs)

        translatable_model = attrs.get('translatable_model', None)

        if translatable_model == (ModelBase,):
            return new_class

        if translatable_model is not None:
            base_formfield_callback = None
            for b in bases:
                if hasattr(b, 'Meta') and hasattr(b.Meta, 'formfield_callback'):
                    base_formfield_callback = b.Meta.formfield_callback
                    break

            formfield_callback = attrs.pop('formfield_callback', base_formfield_callback)
            translatable_fields = translatable_model._get_translatable_fields_names()

            fields = fields_for_model(translatable_model,
                                      fields=translatable_fields,
                                      formfield_callback=formfield_callback,
                                      apply_limit_choices_to=False,
                                      )

            # translatable_model, opts.fields, opts.exclude, opts.widgets,
            # formfield_callback, opts.localized_fields, opts.labels,
            # opts.help_texts, opts.error_messages, opts.field_classes,
            # # limit_choices_to will be applied during ModelForm.__init__().
            # apply_limit_choices_to=False,

            declared_fields = copy.deepcopy(new_class.declared_fields)
            declared_fields.update(fields)

            new_class.base_fields = declared_fields
            new_class.declared_fields = declared_fields

        return new_class
コード例 #52
0
    def handle(self, *fixture_labels, **options):

        if len(fixture_labels) > 0:
            path = fixture_labels[0]
            if not os.path.exists(path):
                print 'Path does not exist:', path
                return

            fields = fields_for_model(Product)
            print 'fields:', fields.keys()
            reader = csv.reader(open(path), delimiter=";")
            self.header = reader.next()
            print 'header', self.header
            columns = list(set(fields.keys()) & set(self.header))
            print 'columns:', columns
            for row in reader:
                id = self.get_value('id', row)
                data = dict([(c, getattr(self, 'resolve_' + c,
                                         self.get_value)(c, row))
                             for c in columns])
                prod = None
                try:
                    prod = Product.objects.get(id=id)
                except Product.DoesNotExist:
                    data['id'] = id
                    pl = Placeholder(slot='product_description')
                    pl.save()
                    data['description'] = pl
                    prod = Product(**data)
                else:
                    Product.objects.filter(id=id).update(**data)
                    prod = Product.objects.get(id=id)

                if prod:
                    prod.save()
                    self.post_create(prod, row)
コード例 #53
0
ファイル: forms.py プロジェクト: pawciobiel/Franklin
    def __init__(self, *args, **kwargs):

        self.user = kwargs['instance']
        self.userinfo = self.user.userinfo

        _retrieve_fields = ('birthdate', 'sex', 'country', 'organization')

        # Retrieve initial (current) data from the User and UserInfo object
        _initial = {}
        #_initial.update(model_to_dict(self.user, _fields))
        _initial.update(model_to_dict(self.userinfo, _retrieve_fields))

        # Pass the initial data to the base
        super(UserInfoForm, self).__init__(initial=_initial, *args, **kwargs)

        # Add these automatically fields from the UserInfo object
        _add_fields = ('country', 'organization')
        self.fields.update(fields_for_model(UserInfo, _add_fields))

        # Set description field to be required
        self.fields['description'].required = True
        self.fields['username'].required = True
        self.fields['username'].unique = True
        self.fields['email'].unique = True
コード例 #54
0
def check_formfield(cls, model, opts, label, field):
    if getattr(cls.form, "base_fields", None):
        try:
            cls.form.base_fields[field]
        except KeyError:
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                                       "is missing from the form." %
                                       (cls.__name__, label, field))
    else:
        fields = fields_for_model(model)
        try:
            fields[field]
        except KeyError:
            if hasattr(model, field) and isinstance(getattr(model, field),
                                                    ListField):
                if isinstance(model._fields[field].field,
                              EmbeddedDocumentField):
                    return
            if hasattr(model, field) and isinstance(getattr(model, field),
                                                    EmbeddedDocumentField):
                return
            raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
                                       "is missing from the form." %
                                       (cls.__name__, label, field))
コード例 #55
0
 def get_model_copy_fields(self):
     if self.model_copy_fields is None:
         form_class = self.get_form_class()
         _model_copy_fields = form_class._meta.fields
         if _model_copy_fields is None:  # __all__ option
             opts = form_class._meta
             _model_copy_fields = list(
                 fields_for_model(
                     opts.model,
                     opts.fields,
                     opts.exclude,
                     opts.widgets,
                     getattr(opts, 'formfield_callback', None),
                     opts.localized_fields,
                     opts.labels,
                     opts.help_texts,
                     opts.error_messages,
                     opts.field_classes,
                     # limit_choices_to will be applied during ModelForm.__init__().
                     apply_limit_choices_to=False,
                 ).keys())
     else:
         _model_copy_fields = self.model_copy_fields
     return _model_copy_fields
コード例 #56
0
def readonly_fields(klass, adm, request, obj):
    """ Helper to get readonly fields for TechMHLUserAdmin and TechAdmin.
	Here we apply our definition of readonly: when a user does not have add or
	delete on a model.  Again Django should have only two permissions: 'modify'
	and 'view', and implicitly a third which is none of the two signifying no
	permission.
	"""
    u = request.user
    perm_add = ''.join(
        [adm.opts.app_label, '.',
         adm.opts.get_add_permission()])
    perm_del = ''.join(
        [adm.opts.app_label, '.',
         adm.opts.get_delete_permission()])
    # Mess with the fields here we can't call get_field_sets() because it calls this
    # function too - I hope django changes the way they do permissions for admin.
    # There should be two: modify, view, and implicitly none for no permissions.
    if not u.is_superuser and not u.has_perm(perm_add) and not u.has_perm(
            perm_del):
        fields = fields_for_model(adm.model)  # grab all fields from the model
    else:
        fields = super(klass, adm).get_readonly_fields(request, obj)

    return fields
コード例 #57
0
ファイル: helpers.py プロジェクト: johnarnfield/django-paypal
from paypal.pro.signals import *
from paypal.pro.models import PayPalNVP, L
from paypal.pro.exceptions import PayPalFailure

TEST = settings.PAYPAL_TEST
USER = settings.PAYPAL_WPP_USER
PASSWORD = settings.PAYPAL_WPP_PASSWORD
SIGNATURE = settings.PAYPAL_WPP_SIGNATURE
VERSION = 54.0
BASE_PARAMS = dict(USER=USER,
                   PWD=PASSWORD,
                   SIGNATURE=SIGNATURE,
                   VERSION=VERSION)
ENDPOINT = "https://api-3t.paypal.com/nvp"
SANDBOX_ENDPOINT = "https://api-3t.sandbox.paypal.com/nvp"
NVP_FIELDS = fields_for_model(PayPalNVP).keys()


def paypal_time(time_obj=None):
    """Returns a time suitable for PayPal time fields."""
    if time_obj is None:
        time_obj = time.gmtime()
    return time.strftime(PayPalNVP.TIMESTAMP_FORMAT, time_obj)


def paypaltime2datetime(s):
    """Convert a PayPal time string to a DateTime."""
    return datetime.datetime(
        *(time.strptime(s, PayPalNVP.TIMESTAMP_FORMAT)[:6]))

コード例 #58
0
ファイル: report.py プロジェクト: pwhipp/django-model-report
    def get_form_filter(self, request):
        form_fields = fields_for_model(
            self.model,
            [f for f in self.get_query_field_names() if f in self.list_filter])
        if not form_fields:
            form_fields = {
                '__all__':
                forms.BooleanField(label='',
                                   widget=forms.HiddenInput,
                                   initial='1')
            }
        else:
            opts = self.model._meta
            for k, v in dict(form_fields).items():
                if v is None:
                    pre_field = None
                    base_model = self.model
                    if '__' in k:
                        # for field_lookup in k.split("__")[:-1]:
                        for field_lookup in k.split("__"):
                            if pre_field:
                                if isinstance(pre_field, RelatedObject):
                                    base_model = pre_field.model
                                else:
                                    base_model = pre_field.rel.to
                            pre_field = base_model._meta.get_field_by_name(
                                field_lookup)[0]

                        model_field = pre_field
                    else:
                        field_name = k.split("__")[0]
                        model_field = opts.get_field_by_name(field_name)[0]

                    if isinstance(model_field, (DateField, DateTimeField)):
                        form_fields.pop(k)
                        field = RangeField(model_field.formfield)
                    else:
                        if not hasattr(model_field, 'formfield'):
                            field = forms.ModelChoiceField(
                                queryset=model_field.model.objects.all())
                            field.label = self.override_field_labels.get(
                                k, base_label
                            )(
                                self, field
                            ) if k in self.override_field_labels else field_lookup

                        elif isinstance(model_field, ForeignKey):
                            field = model_field.formfield()

                            if self.always_show_full_username and (
                                    model_field.rel.to == User):
                                field.label_from_instance = self.get_user_label

                            if self.list_filter_queryset:
                                for query_field, query in self.list_filter_queryset.iteritems(
                                ):
                                    if query_field == k:
                                        for variable, value in query.iteritems(
                                        ):
                                            field.queryset = field.queryset.filter(
                                                **{variable: value})

                        else:
                            field = model_field.formfield()
                            if self.list_filter_widget.has_key(k):
                                use_widget, widget, field_class = self.check_for_widget(
                                    self.list_filter_widget, k)
                                if use_widget:
                                    field.__class__ = field_class
                                    field.widget = widget
                                    field.choices = model_field.choices
                                    field.choices.insert(0, ('', '---------'))
                                    field.initial = ''

                        field.label = force_unicode(_(field.label))

                else:
                    if isinstance(v, (forms.BooleanField)):
                        form_fields.pop(k)
                        field = forms.ChoiceField()
                        field.label = v.label
                        field.help_text = v.help_text
                        field.choices = (
                            ('', ''),
                            (True, _('Yes')),
                            (False, _('No')),
                        )
                        setattr(field, 'as_boolean', True)
                    elif isinstance(v, (forms.DateField, forms.DateTimeField)):
                        field_name = k.split("__")[0]
                        model_field = opts.get_field_by_name(field_name)[0]
                        form_fields.pop(k)
                        field = RangeField(model_field.formfield)
                    else:
                        field = v

                    if hasattr(field, 'choices'):
                        if not hasattr(field, 'queryset'):
                            if field.choices[0][0]:
                                field.choices.insert(0, ('', '---------'))
                                field.initial = ''

                # Provide a hook for updating the queryset
                if hasattr(field,
                           'queryset') and k in self.override_field_choices:
                    field.queryset = self.override_field_choices.get(k)(
                        self, field.queryset)
                form_fields[k] = field

        FilterFormClass = type('FilterFormBase', (FilterForm, ),
                               {'base_fields': form_fields})
        form = FilterFormClass(data=request.GET or None)
        form.is_valid()
        return form
コード例 #59
0
 class Meta:
     model = models.Employee
     fields = fields_for_model(models.Employee).keys()
     widgets = {'user': autocomplete.ModelSelect2('select_user')}
コード例 #60
0
 def test_empty_fields_to_fields_for_model(self):
     "An argument of fields=() to fields_for_model should return an empty dictionary"
     field_dict = fields_for_model(Person, fields=())
     self.assertEqual(len(field_dict), 0)