コード例 #1
0
ファイル: forms.py プロジェクト: MissHead/ideax
class IdeaForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        queryset = kwargs.pop('authors', None)
        super(IdeaForm, self).__init__(*args, **kwargs)
        self.fields['authors'] = forms.ModelMultipleChoiceField(
            queryset=queryset,
            widget=FilteredSelectMultiple("", is_stacked=False),
            required=False,
            label=_('Coauthors'))

    challenge = forms.ModelChoiceField(
        queryset=Challenge.objects.filter(discarted=False),
        empty_label=_('Not related to any challenge'),
        required=False,
        label=_('Challenge'))
    oportunity = MartorFormField(label=_('Oportunity'))
    solution = MartorFormField(label=_('Solution'))
    target = MartorFormField(label=_('Target'))
    summary = MartorFormField(label=_('Summary'))

    class Meta:
        model = Idea
        fields = ('title', 'summary', 'oportunity', 'solution', 'target',
                  'category', 'challenge', 'authors')
        labels = {'title': _('Title'), 'category': _('Category')}

    class Media:
        css = {
            'all': (os.path.join(settings.BASE_DIR,
                                 '/static/admin/css/widgets.css')),
        }
        js = ('/admin/jsi18n', 'jquery.js', 'jquery.init.js', 'core.js',
              'SelectBox.js', 'SelectFilter2.js')
コード例 #2
0
ファイル: forms.py プロジェクト: TheSeems/TReports
class ReportForm(ModelForm):
    steps = MartorFormField()

    class Meta:
        model = Report
        fields = ('name', 'steps', 'fact', 'expect', 'tags', 'author', 'status', 'open', 'comments')
        widgets = {'steps': Textarea}
コード例 #3
0
ファイル: forms.py プロジェクト: 23yashm/cdcrc_website
class ResourceForm(forms.ModelForm):
    detail = MartorFormField()

    class Meta:
        model = Resource
        fields = ['title', 'categories', 'url', 'brief', 'detail']
        labels = {
            'title': 'Title *',
            'categories': 'Categories (Multiple)*',
            'url': 'URL',
            'brief': 'Brief Overview*',
            # 'detail': '',
        }
        widgets = {
            'title':
            forms.TextInput(attrs={
                'class': 'form-control',
                'required': True
            }),
            'categories':
            forms.SelectMultiple(attrs={
                'class': 'form-control',
                'required': True,
            }),
            'url':
            forms.TextInput(attrs={
                'class': 'form-control',
            }),
            'brief':
            forms.TextInput(attrs={
                'class': 'form-control',
                'required': True,
            }),
        }
コード例 #4
0
ファイル: forms.py プロジェクト: TheSeems/TReports
class CommentForm(ModelForm):
    content = MartorFormField()
    report_id = IntegerField()

    class Meta:
        model = Comment
        fields = ('content',)
コード例 #5
0
ファイル: forms.py プロジェクト: MissHead/ideax
class ChallengeForm(forms.ModelForm):
    description = MartorFormField()

    class Meta:
        model = Challenge
        fields = (
            'title',
            'image',
            'summary',
            'requester',
            'description',
            'active',
            'limit_date',
            'featured',
            'category',
        )
        labels = {
            'title': _('Title'),
            'image': _('Image'),
            'summary': _('Summary'),
            'requester': _('Requester'),
            'description': _('Description'),
            'active': _('Active'),
            'limit_date': _('Limit Date'),
            'featured': _('Featured'),
            'category': _('Category')
        }
        widgets = {
            'limit_date': forms.DateInput(attrs={'placeholder': 'dd/mm/aaaa'}),
        }
コード例 #6
0
ファイル: form.py プロジェクト: whinyadventure/RNA-Puzzles
class Form(forms.ModelForm):

    group_description = MartorFormField(required=False)

    def __init__(self, *args, **kwargs):
        super(Form, self).__init__(*args, **kwargs)
        self.request = kwargs['initial']['request']
        user = CustomUser.objects.get(id=self.request.user.id)
        group = Group.objects.get(group_name=kwargs['instance'])

        if not user.has_perm("name_group", group):
            self.fields["group_name"].widget = forms.HiddenInput()
            self.fields["contact"].widget = forms.HiddenInput()

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Row(Column('group_name',
                       css_class='form-group col-md-4 mb-0 offset-md-4'),
                css_class='form-row'),
            Row(Column('contact',
                       css_class='form-group col-md-4 mb-0 offset-md-4'),
                css_class='form-row '),
            Row(Column('group_description', css_class='form-group'),
                css_class='form-row justify-content-center custom-martor'),
            Row(Submit('submit', 'Save', css_class="custom-button"),
                css_class='form-row flex-d justify-content-center'))

    class Meta:
        model = Group
        fields = ["group_name", "contact", "group_description"]
コード例 #7
0
ファイル: forms.py プロジェクト: castin1010/dolife
class AuthorForm(forms.ModelForm):
    """ Used to create or edit a story.  It picks up on inspired_by via 2 mechanisms """

    bio_text = MartorFormField(label=_('Biography'), required=False)

    class Meta:
        model = Author
        fields = ['name', 'bio_text', 'avatar']

    def __init__(self, *args, user, **kwargs):
        super(AuthorForm, self).__init__(*args, **kwargs)

        width = Author._meta.get_field('name').max_length
        self.fields['name'].widget.attrs['size'] = width
        self.fields['bio_text'].widget.attrs['cols'] = width

        self.user = user

    def save(self, commit=True):
        """ Add the user to the object before we persist it """
        obj = super(AuthorForm, self).save(commit=False)
        obj.user = self.user

        if commit:
            obj.save()
            self.save_m2m()
        return obj
コード例 #8
0
ファイル: forms.py プロジェクト: GitBib/django-wiki
class CreateForm(forms.Form, SpamProtectionMixin):
    def __init__(self, request, urlpath_parent, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.urlpath_parent = urlpath_parent

    title = forms.CharField(label=_('Title'), )
    slug = WikiSlugField(
        label=_('Slug'),
        help_text=
        _("This will be the address where your article can be found. Use only alphanumeric characters and - or _.<br>Note: If you change the slug later on, links pointing to this article are <b>not</b> updated."
          ),
        max_length=models.URLPath.SLUG_MAX_LENGTH)
    content = MartorFormField(
        label=_('Contents'), required=False,
        widget=getEditor().get_widget())  # @UndefinedVariable

    summary = forms.CharField(
        label=pgettext_lazy('Revision comment', 'Summary'),
        help_text=_("Write a brief message for the article's history log."),
        required=False)

    def clean_slug(self):
        return _clean_slug(self.cleaned_data['slug'], self.urlpath_parent)

    def clean(self):
        super().clean()
        self.check_spam()
        return self.cleaned_data
コード例 #9
0
class NewBlogForm(ModelForm):
    author = ModelChoiceField(queryset=Author.objects.all(), )
    blog_in_markdown = MartorFormField()

    class Meta:
        model = Blog
        fields = ["author", "title", "blog_in_markdown"]
コード例 #10
0
ファイル: forms.py プロジェクト: Jokotoye18/Forum
class NewTopicForm(forms.ModelForm):
    subject = MartorFormField()
    class Meta:
        model = Topic
        fields = ['topic', 'subject',]
        widgets = {
            "topic": forms.TextInput(attrs={"placeholder":"Topic"}),
        }
コード例 #11
0
class BlogModelForm(forms.ModelForm):
    content = MartorFormField()

    class Meta:
        model = Blog
        fields = [
            'title', 'content', 'category', 'image', 'alt_text', 'youtube'
        ]
コード例 #12
0
class RecipeForm(forms.ModelForm):
    recipe = MartorFormField()

    class Meta:
        model = Recipe
        fields = '__all__'
        widgets = {
            'tags': autocomplete.ModelSelect2Multiple(url='autocomplete-tag'),
        }
コード例 #13
0
class SimpleForm(
        forms.Form
):  # use forms.ModelForm instead forms.Form and erase all following entry
    title = forms.CharField(widget=forms.TextInput())
    description = MartorFormField()

    #wiki = MartorFormField()

    class Meta():  # it is created by sk
        model = Simple
        fields = '__all__'
コード例 #14
0
ファイル: forms.py プロジェクト: 21jordanmorris/theFans
class PostForm(forms.ModelForm):
    content = MartorFormField()

    class Meta:
        model = Post
        fields = [
            "title",
            "writer",
            "summary",
            "content",
            "sport",
            "image",
        ]
コード例 #15
0
class NewsForms(forms.ModelForm):
    content = MartorFormField()
    picture_id = forms.ModelChoiceField(Picture.objects.all(),
                                        widget=PictureSelect(),
                                        required=False)
    publish_date = forms.SplitDateTimeField(widget=MySplitDateTimeWidget(
        attrs={
            'date_class': 'datepicker',
            'time_class': 'timepicker'
        }))

    class Meta:
        model = News
        fields = ('title', 'picture_id', 'content', 'publish_date')
コード例 #16
0
class Form(forms.ModelForm):

    success_url = ""

    title = forms.CharField()
    description = MartorFormField()

    helper = FormHelper()
    helper.form_id = 'Faq_form'
    helper.add_input(Submit('submit', 'Submit', css_class='btn-primary'))
    helper.form_method = 'POST'

    def __init__(self, *args, **kwargs):
        super(Form, self).__init__(*args, **kwargs)

    class Meta:
        model = FaqModel
        fields = ["title", "description"]
コード例 #17
0
class CodePostForm(forms.ModelForm):
    title = forms.CharField(label='글 제목',
                            label_suffix='',
                            widget=forms.TextInput(attrs={
                                'placeholder': '글 제목을 입력하세요.',
                                'class': 'form',
                            }))
    content = MartorFormField()
    password = forms.CharField(
        label='글 비밀번호 설정',
        label_suffix='',
        widget=forms.PasswordInput(attrs={
            'class': 'form password-form',
        }))

    class Meta:
        model = CodePost
        fields = ['title', 'content', 'password']
コード例 #18
0
ファイル: forms.py プロジェクト: basraah/allianceauth-bbs
class TopicForm(forms.ModelForm):
    content = MartorFormField()

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = user
        self.fields['category'].queryset = models.Category.objects.all(
        ).visible_for_user(user)

    @transaction.atomic
    def save(self, commit=True):
        instance = super().save()
        post = models.Post()
        post.content = self.cleaned_data.get('content')
        post.created_by = self.user
        post.topic = instance
        post.save()
        return instance

    class Meta:
        model = models.Topic
        fields = ('title', 'category', 'content')
コード例 #19
0
class PostForm(forms.Form):
    description = MartorFormField()
コード例 #20
0
ファイル: forms.py プロジェクト: TKCERT/dfirtrack
class ReportitemForm(forms.ModelForm):
    """ default model form """

    # reorder field choices
    case = forms.ModelChoiceField(
        label = gettext_lazy('Corresponding case'),
        queryset = Case.objects.order_by('case_name'),
        required = False,
        empty_label = 'Select case (optional)',
    )

    # reorder field choices
    headline = forms.ModelChoiceField(
        label = gettext_lazy('Headline (*)'),
        empty_label = 'Select headline',
        queryset = Headline.objects.order_by('headline_name'),
    )

    reportitem_note = MartorFormField(
        label = gettext_lazy('Note (*)'),
    )

    # reorder field choices
    notestatus = forms.ModelChoiceField(
        queryset = Notestatus.objects.order_by('notestatus_name'),
        label = 'Notestatus (*)',
        required = True,
        widget = forms.RadioSelect(),
    )

    # reorder field choices
    system = forms.ModelChoiceField(
        label = gettext_lazy('System (*)'),
        empty_label = 'Select system',
        queryset = System.objects.order_by('system_name'),
    )

    # reorder field choices
    tag = forms.ModelMultipleChoiceField(
        label = gettext_lazy('Tags'),
        widget=TagWidget,
        queryset=Tag.objects.order_by('tag_name'),
        required=False,
    )

    class Meta:

        # model
        model = Reportitem

        # this HTML forms are shown
        fields = (
            'case',
            'headline',
            'notestatus',
            'system',
            'tag',
            'reportitem_subheadline',
            'reportitem_note',
        )

        # non default form labeling
        labels = {
            'reportitem_subheadline': gettext_lazy('Subheadline'),
        }

        # special form type or option
        widgets = {
            'reportitem_note': forms.Textarea(attrs={
                'autofocus': 'autofocus',
                'rows': 20,
                'style': 'font-family: monospace',
            }),
        }
コード例 #21
0
ファイル: forms.py プロジェクト: TKCERT/dfirtrack
class NoteForm(forms.ModelForm):
    """ default model form """

    # make hidden version field to make custom field validation work
    note_version = forms.CharField(
        widget=forms.HiddenInput,
        required=False,
    )

    # make hidden id field to make custom field validation work
    note_id = forms.CharField(
        widget=forms.HiddenInput,
        required=False,
    )

    # markdown field
    note_content = MartorFormField(
        label = gettext_lazy('Note (*)'),
    )

    # reorder field choices
    case = forms.ModelChoiceField(
        label = gettext_lazy('Corresponding case'),
        queryset = Case.objects.order_by('case_name'),
        required = False,
        empty_label = 'Select case (optional)',
    )

    # reorder field choices
    notestatus = forms.ModelChoiceField(
        queryset = Notestatus.objects.order_by('notestatus_name'),
        label = 'Notestatus (*)',
        required = True,
        widget = forms.RadioSelect(),
    )

    # reorder field choices
    tag = forms.ModelMultipleChoiceField(
        label = gettext_lazy('Tags'),
        widget=TagWidget,
        queryset=Tag.objects.order_by('tag_name'),
        required=False,
    )

    def clean_note_version(self):
        """ custom field validation to prevent accidental overwriting between analysts """

        note_version = self.cleaned_data['note_version']
        if note_version != '':
            note_id = self.initial['note_id']
            current_version = Note.objects.get(note_id=note_id)
            if int(note_version)+1 <= current_version.note_version:
                raise ValidationError('There is a newer version of this note.')
        return note_version

    class Meta:

        # model
        model = Note

        # this HTML forms are shown
        fields = (
            'note_id',
            'note_title',
            'note_content',
            'tag',
            'case',
            'note_version',
            'notestatus',
        )

        # non default form labeling
        labels = {
            'note_title': gettext_lazy('Note title (*)'),
        }

        # special form type or option
        widgets = {
            'note_title': forms.TextInput(attrs={'autofocus': 'autofocus'}),
        }
コード例 #22
0
ファイル: forms.py プロジェクト: soulwawa/mysite
class PostForm(forms.Form):
    contents = MartorFormField()
コード例 #23
0
class SimpleForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput())
    description = MartorFormField()
    wiki = MartorFormField()
コード例 #24
0
class UnitForm(forms.Form):
    unit_name = forms.CharField(
        label="Name",
        max_length=200,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Enter unit name"
        }),
        required=False,
    )
    unit_short_name = forms.CharField(
        label=UNIT_SINGULAR + " short name",
        max_length=10,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Enter short name"
        }),
        required=False,
    )
    unit_overview = MartorFormField(
        label="Overview",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter unit overview",
        }),
        required=False,
    )
    unit_outcome = forms.ModelMultipleChoiceField(
        label="Outcomes",
        queryset=Outcome.objects.all(),
        widget=FilteredSelectMultiple(verbose_name="Outcomes",
                                      is_stacked=False),
        required=False,
    )
    unit_objective = forms.ModelMultipleChoiceField(
        label="Objectives",
        queryset=Objective.objects.all(),
        widget=FilteredSelectMultiple(verbose_name="Objectives",
                                      is_stacked=False),
        required=False,
    )
    unit_body = MartorFormField(
        label="Body",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter unit body"
        }),
        required=False,
    )
    unit_resources = MartorFormField(
        label="Resources",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter unit resources",
        }),
        required=False,
    )
    unit_test = MartorFormField(
        label="Test",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter unit test"
        }),
        required=False,
    )
    module = forms.ModelMultipleChoiceField(
        label=MODULE_PLURAL,
        queryset=Module.objects.all(),
        widget=FilteredSelectMultiple(verbose_name=MODULE_PLURAL,
                                      is_stacked=False),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super(UnitForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = "POST"
        self.helper.add_input(Submit("submit", "Submit"))
コード例 #25
0
class CourseForm(forms.Form):
    course_id = forms.CharField(
        label=COURSE_SINGULAR + " id",
        max_length=20,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Enter course id"
        }),
        required=True,
    )
    course_title = forms.CharField(
        label="Title",
        max_length=200,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Enter course title"
        }),
        required=True,
    )
    course_short_name = forms.CharField(
        label=COURSE_SINGULAR + " short name",
        max_length=10,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": "Enter short name"
        }),
        required=False,
    )
    course_overview = MartorFormField(
        label="Overview",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter course overview",
        }),
        required=False,
    )
    course_outcome = forms.ModelMultipleChoiceField(
        label="Outcomes",
        queryset=Outcome.objects.all(),
        widget=FilteredSelectMultiple(verbose_name="Outcomes",
                                      is_stacked=False),
        required=False,
    )
    course_objective = forms.ModelMultipleChoiceField(
        label="Objectives",
        queryset=Objective.objects.all(),
        widget=FilteredSelectMultiple(verbose_name="Objectives",
                                      is_stacked=False),
        required=False,
    )
    course_credit = forms.IntegerField(
        label="Credit",
        max_value=1000,
        min_value=1,
        widget=forms.NumberInput(attrs={
            "class": "form-control",
            "placeholder": "Enter course credits",
        }),
        required=True,
    )
    lecture_contact_hours_per_week = forms.IntegerField(
        label="Lecture contact hours per week",
        max_value=1000,
        min_value=0,
        widget=forms.NumberInput(
            attrs={
                "class": "form-control",
                "placeholder": "Enter lecture contact hours",
            }),
        required=True,
    )
    tutorial_contact_hours_per_week = forms.IntegerField(
        label="Tutorial contact hours per week",
        max_value=1000,
        min_value=0,
        widget=forms.NumberInput(
            attrs={
                "class": "form-control",
                "placeholder": "Enter tutorial contact hours",
            }),
        required=True,
    )
    practical_contact_hours_per_week = forms.IntegerField(
        label="Practical contact hours per week",
        max_value=1000,
        min_value=0,
        widget=forms.NumberInput(
            attrs={
                "class": "form-control",
                "placeholder": "Enter practical contact hours",
            }),
        required=True,
    )
    course_resources = MartorFormField(
        label="Resources",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter course resources",
        }),
        required=False,
    )
    course_test = MartorFormField(
        label="Test",
        widget=forms.Textarea(attrs={
            "class": "form-control",
            "placeholder": "Enter course test"
        }),
        required=False,
    )
    discipline = forms.ModelMultipleChoiceField(
        label=DISCIPLINE_PLURAL,
        queryset=Discipline.objects.all(),
        widget=FilteredSelectMultiple(verbose_name=DISCIPLINE_PLURAL,
                                      is_stacked=False),
        required=False,
    )

    class Meta:
        model = Course
        exclude = []

    def __init__(self, *args, **kwargs):
        super(CourseForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = "POST"
        self.helper.form_class = "form-horizontal"
        self.helper.label_class = "col-md-3"
        self.helper.field_class = "col-md-9"
        self.helper.layout = Layout(
            Div(
                Field("course_id"),
                HTML("<br>"),
                Field("course_title"),
                HTML("<br>"),
                Field("course_short_name"),
                HTML("<br>"),
                Field("course_overview"),
                HTML("<br>"),
                Fieldset("Add Outcomes", FormsetLayoutObject("outcomes")),
                HTML("<br>"),
                Field("course_objective"),
                HTML("<br>"),
                Field("course_credit"),
                HTML("<br>"),
                Field("lecture_contact_hours_per_week"),
                HTML("<br>"),
                Field("tutorial_contact_hours_per_week"),
                HTML("<br>"),
                Field("practical_contact_hours_per_week"),
                HTML("<br>"),
                Field("course_resources"),
                HTML("<br>"),
                Field("course_test"),
                HTML("<br>"),
                Field("discipline"),
                HTML("<br>"),
                ButtonHolder(Submit("submit", "Submit")),
            ))
コード例 #26
0
ファイル: martor.py プロジェクト: agusmakmun/python.web.id
class MartorDemoForm(forms.Form):
    description = MartorFormField()
コード例 #27
0
ファイル: forms.py プロジェクト: GitBib/django-wiki
class EditForm(forms.Form, SpamProtectionMixin):

    title = forms.CharField(label=_('Title'), )
    content = MartorFormField(
        label=_('Contents'), required=False,
        widget=getEditor().get_widget())  # @UndefinedVariable

    summary = forms.CharField(
        label=pgettext_lazy('Revision comment', 'Summary'),
        help_text=
        _('Give a short reason for your edit, which will be stated in the revision log.'
          ),
        required=False)

    current_revision = forms.IntegerField(required=False,
                                          widget=forms.HiddenInput())

    def __init__(self, request, current_revision, *args, **kwargs):

        self.request = request
        self.no_clean = kwargs.pop('no_clean', False)
        self.preview = kwargs.pop('preview', False)
        self.initial_revision = current_revision
        self.presumed_revision = None
        if current_revision:
            initial = {
                'content': current_revision.content,
                'title': current_revision.title,
                'current_revision': current_revision.id
            }
            initial.update(kwargs.get('initial', {}))

            # Manipulate any data put in args[0] such that the current_revision
            # is reset to match the actual current revision.
            data = None
            if len(args) > 0:
                data = args[0]
                args = args[1:]
            if data is None:
                data = kwargs.get('data', None)
            if data:
                self.presumed_revision = data.get('current_revision', None)
                if not str(self.presumed_revision) == str(
                        self.initial_revision.id):
                    newdata = {}
                    for k, v in data.items():
                        newdata[k] = v
                    newdata['current_revision'] = self.initial_revision.id
                    newdata['content'] = simple_merge(
                        self.initial_revision.content, data.get('content', ""))
                    newdata['title'] = current_revision.title
                    kwargs['data'] = newdata
                else:
                    # Always pass as kwarg
                    kwargs['data'] = data

            kwargs['initial'] = initial

        super().__init__(*args, **kwargs)

    def clean_title(self):
        title = self.cleaned_data.get('title', None)
        title = (title or "").strip()
        if not title:
            raise forms.ValidationError(
                gettext('Article is missing title or has an invalid title'))
        return title

    def clean(self):
        """Validates form data by checking for the following
        No new revisions have been created since user attempted to edit
        Revision title or content has changed
        """
        cd = super().clean()
        if self.no_clean or self.preview:
            return cd
        if not str(self.initial_revision.id) == str(self.presumed_revision):
            raise forms.ValidationError(
                gettext(
                    'While you were editing, someone else changed the revision. Your contents have been automatically merged with the new contents. Please review the text below.'
                ))
        if ('title'
                in cd) and cd['title'] == self.initial_revision.title and cd[
                    'content'] == self.initial_revision.content:
            raise forms.ValidationError(
                gettext('No changes made. Nothing to save.'))
        self.check_spam()
        return cd
コード例 #28
0
class StoryForm(forms.ModelForm):
    """ Used to create or edit a story.  It picks up on inspired_by via 2 mechanisms """

    text = MartorFormField(label=_('Story'), required=True)
    author = forms.ModelChoiceField(label=_('Pseudonym'),
                                    queryset=None,
                                    required=True)
    private = forms.BooleanField(required=False)
    inspired_by = InspiredByIdField(required=False, queryset=None)

    class Meta:
        model = Story
        fields = [
            'author', 'title', 'tagline', 'text', 'inspired_by', 'private'
        ]

    def get_inspired_by_id(self):
        """ We can get a value for inspired_by from the initial or the instance and it might be an
              int or an instance.  Hide all of that here."""
        if self.instance and self.instance.inspired_by:
            return self.instance.inspired_by.id
        else:
            inspired_by = self.initial.get('inspired_by',
                                           self.data.get('inspired_by', None))
            if inspired_by:
                if isinstance(inspired_by, Story):
                    return inspired_by.id
                else:
                    return int(inspired_by)

        return None

    def __init__(self, *args, user, **kwargs):
        super(StoryForm, self).__init__(*args, **kwargs)

        width = Story._meta.get_field('title').max_length
        self.fields['title'].widget.attrs['size'] = width
        self.fields['tagline'].widget.attrs['size'] = width
        self.fields['text'].widget.attrs['cols'] = width

        self.fields['author'].queryset = Author.objects.for_user(user)

        inspired_by_id = self.get_inspired_by_id()

        if inspired_by_id:
            self.fields['inspired_by'].queryset = Story.objects.filter(
                pk=inspired_by_id)
        else:
            # The user cannot supply a value for inspired by (only check the box)
            #   Remove the field if there is no inspired_by value to check the box for
            del self.fields['inspired_by']

    def save(self, commit=True):

        obj = super(StoryForm, self).save(commit=False)

        if self.cleaned_data['private']:
            obj.published_at = None
        elif not obj.published_at:
            obj.published_at = timezone.now()

        if commit:
            obj.save()
            self.save_m2m()
        return obj
コード例 #29
0
class ChallengeForm(forms.ModelForm):
    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

    description = MartorFormField(
        label=_('Description'),
        max_length=Challenge._meta.get_field('description').max_length)

    class Meta:
        model = Challenge
        fields = (
            'title',
            'image',
            'x',
            'y',
            'width',
            'height',
            'summary',
            'requester',
            'description',
            'active',
            'limit_date',
            'init_date',
            'featured',
            'category',
        )
        labels = {
            'title': _('Title'),
            'image': _('Image'),
            'summary': _('Summary'),
            'requester': _('Requester'),
            'active': _('Active'),
            'limit_date': _('Limit Date'),
            'init_date': _('Init Date'),
            'featured': _('Featured'),
            'category': _('Category')
        }
        widgets = {
            'limit_date': forms.DateInput(attrs={'placeholder': 'dd/mm/aaaa'}),
            'init_date': forms.DateInput(attrs={'placeholder': 'dd/mm/aaaa'}),
        }

    def save(self):
        data = self.cleaned_data

        challenge = Challenge(title=data['title'],
                              image=data['image'],
                              summary=data['summary'],
                              requester=data['requester'],
                              description=data['description'],
                              limit_date=data['limit_date'],
                              init_date=data['init_date'],
                              active=data['active'],
                              featured=data['featured'],
                              category=data['category'],
                              discarted=False)

        x = self.cleaned_data.get('x')
        y = self.cleaned_data.get('y')
        w = self.cleaned_data.get('width')
        h = self.cleaned_data.get('height')

        image = Image.open(challenge.image)
        cropped_image = image.crop((x, y, w + x, h + y))

        img_path = challenge.image.path.split('/')
        img_name = img_path.pop()
        img_path.append('challenges')
        img_path.append(img_name)
        img_path = "/".join(img_path)

        cropped_image.save(img_path, format='JPEG', subsampling=0, quality=100)

        challenge.image = '/challenges/' + img_name

        return challenge
コード例 #30
0
ファイル: forms.py プロジェクト: TheSeems/TReports
class UserReportForm(ModelForm):
    steps = MartorFormField()

    class Meta:
        model = Report
        fields = ('name', 'steps', 'fact', 'expect', 'tags')