Beispiel #1
0
    def test_widget(self):
        from django_summernote.widgets import SummernoteWidget

        widget = SummernoteWidget()
        html = widget.render("foobar", "lorem ipsum", attrs={"id": "id_foobar"})
        url = reverse("django_summernote-editor", kwargs={"id": "id_foobar"})

        assert url in html
        assert 'id="id_foobar"' in html
Beispiel #2
0
    def test_config_allow_blank_values(self):
        from django_summernote.widgets import SummernoteWidget

        summernote_config['summernote']['tableClassName'] = ''

        widget = SummernoteWidget()
        html = widget.render(
            'foobar', 'lorem ipsum', attrs={'id': 'id_foobar'}
        )
        assert '"tableClassName": ""' in html
Beispiel #3
0
    def test_widget(self):
        from django_summernote.widgets import SummernoteWidget

        widget = SummernoteWidget()
        html = widget.render(
            'foobar', 'lorem ipsum', attrs={'id': 'id_foobar'}
        )
        url = reverse('django_summernote-editor', kwargs={'id': 'id_foobar'})

        assert url in html
        assert 'id="id_foobar"' in html
Beispiel #4
0
class SignUpForm(UserCreationForm):
    email = forms.EmailField()
    confirm_email = forms.EmailField()
    contact = forms.RegexField(regex="^[6-9]\d{9}", required=False)
    bio = forms.CharField(widget=SummernoteWidget())

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'username', 'email',
                  'confirm_email', 'contact', 'category', 'password1',
                  'password2', 'image', 'bio')

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get('email') != cleaned_data.get('confirm_email'):
            raise forms.ValidationError(
                'Your Email and Confirm Email is not match', code='Invalid')
Beispiel #5
0
    def test_widgets_with_attributes(self):
        from django_summernote.widgets import (SummernoteWidget,
                                               SummernoteInplaceWidget)

        widget = SummernoteInplaceWidget(attrs={'class': 'special'})
        html = widget.render('foobar',
                             'lorem ipsum',
                             attrs={'id': 'id_foobar'})

        assert 'class="special"' in html

        widget = SummernoteWidget(attrs={'class': 'special'})
        html = widget.render('foobar',
                             'lorem ipsum',
                             attrs={'id': 'id_foobar'})

        assert 'class="special"' in html
Beispiel #6
0
class FreePostForm(forms.ModelForm):
    class Meta:
        model = FreePost
        fields = (
            'title',
            'content',
        )

    title = forms.CharField(required=True,
                            max_length=300,
                            widget=forms.TextInput(attrs={
                                'class': 'new-title',
                                'placeholder': 'Title',
                            }))
    content = forms.CharField(widget=SummernoteWidget(attrs={
        'placeholder': 'Content',
    }))
Beispiel #7
0
class EnviarEmailForm(forms.Form):
    asunto = forms.CharField(max_length=200)
    template = forms.CharField(widget=SummernoteWidget())

    def clean_template(self):
        template = self.cleaned_data['template']
        django_engine = engines['django']
        try:
            template = django_engine.from_string(
                '{% extends "fiscales/base_email.html" %}'
                '{% block body %}'
                f'{template}'
                '{% endblock body %}')
        except Exception as e:
            raise forms.ValidationError(str(e))

        return template
Beispiel #8
0
class PictureForm(forms.ModelForm):
    content = forms.CharField(widget=SummernoteWidget())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        class_update_fields = ['title', 'content']
        for field_name in class_update_fields:
            self.fields[field_name].widget.attrs.update({
                'class': 'form-control'
            })

        self.fields['title'].label = _('제목')
        self.fields['content'].label = _('내용')

    class Meta:
        model = Picture
        fields = ['title', 'content']
Beispiel #9
0
    class Meta:
        model = Post
        fields = [
            'title',
            'text',
        ]

        widgets = {
            'title':
            forms.TextInput(
                attrs={
                    'class': 'w-100 form-control form-control-sm',
                    'placeholder': 'Title'
                }),
            'text':
            SummernoteWidget(),
        }
Beispiel #10
0
    class Meta:
        model = Comment
        fields = (
            'author',
            'text',
        )

        widgets = {
            'author':
            forms.TextInput(
                attrs={
                    'class': 'w-100 form-control form-control-sm',
                    'placeholder': 'author'
                }),
            'text':
            SummernoteWidget(),
        }
Beispiel #11
0
class PostCreateForm(forms.ModelForm):
    content = forms.CharField(widget=SummernoteWidget())

    class Meta:
        model = Post
        fields = ('title', 'content', 'status', 'category', 'image_url',
                  'image')

    def clean_title(self):
        cleaned_data = super().clean()
        title = cleaned_data.get('title')
        slug = slugify(title)
        try:
            post_obj = Post.objects.get(slug=slug)
            raise forms.ValidationError("Title is already exits",
                                        code='Invalid')
        except ObjectDoesNotExist:
            return title
Beispiel #12
0
	class Meta:
		model = Post
		fields = ['title', 'slug', 'body', 'tags']


		widgets = {
			'title': forms.TextInput(attrs={'class': 'form-control'}),
			'slug': forms.TextInput(attrs={'class': 'form-control'}),
			'body': SummernoteWidget(),
			'tags': forms.SelectMultiple(attrs={'class': 'form-control'}),
		}

		def clean_slug(self):
			new_slug = self.cleaned_data['slug'].lower()

			if new_slug == 'create':
				raise ValidationError('Slug may not be "Create"')
			return new_slug
Beispiel #13
0
 class Meta:
     model = Post
     fields = [
         'category', 'title', 'contents', 'reference', 'start_date', 'end_date', 'photo', 'tags', 'score'
     ]
     widgets = {
         'contents': SummernoteWidget(),
         'score': starWidget,
         'photo': FileInput(),
     }
     help_texts = {
         'tags': '띄어쓰기 없이 반점(,)을 이용하여 태그를 구별하세요. 최대 10개까지 입력됩니다.',
         'score': '추천도를 반드시 입력해주시기 바랍니다(1점~5점).'
     }
     labels = {
         'tags': '태그',
     }
     '''
Beispiel #14
0
    class Meta:
        """Meta for ModelForm"""

        CATEGORY = ()
        model = Board
        exclude = ('table', 'user', 'created_at', 'modified_at', 'ip',
                   'view_count', 'like_count', 'dislike_count', 'reply_count',
                   'like_users', 'dislike_users')
        widgets = {
            'subject':
            forms.TextInput(attrs={'placeholder': _('Enter title here.')}),
            'reference':
            forms.TextInput(attrs={'placeholder': _('Add a reference URL.')}),
            'category':
            forms.Select(choices=CATEGORY),
            'content':
            SummernoteWidget(),
        }
Beispiel #15
0
class ArticleEditForm(forms.Form):
    """
    記事編集画面Form
    """
    article_title = forms.CharField(label="タイトル", max_length=100)
    article_body = forms.CharField(widget=SummernoteWidget())

    def set_init(self, request, article_id):
        """
        初期化
        :param request:
        :param article_id:
        :return:
        """
        super(ArticleEditForm, self).__init__()
        article = Article.objects.get(id=article_id)
        self.fields["article_title"].initial = article.title
        self.fields["article_body"].initial = article.body
Beispiel #16
0
class PostCreateForm(forms.ModelForm):
    content = forms.CharField(widget=SummernoteWidget(attrs={
        'width': '20%',
        'height': '500px'
    }), )

    class Meta:
        model = Post
        fields = (
            'title',
            'overview',
            'content',
            'thumbnail',
            'categories',
            'featured',
            'previous_post',
            'next_post',
        )
Beispiel #17
0
    def __init__(self,
                 user=None,
                 ad_type=None,
                 text_widget_attrs=None,
                 *args,
                 **kwargs):
        super(PideModelForm, self).__init__(*args, **kwargs)
        if user is not None and ad_type is not None:
            self.fields['ad_from'].queryset = Ad.objects.filter(
                uid=user, ad_type=ad_type, is_archived=False)
        else:
            self.fields['ad_from'] = None

        self.fields['comment'].widget = SummernoteWidget(
            attrs={
                'summernote':
                text_widget_attrs if text_widget_attrs is not None else {}
            })
Beispiel #18
0
class AnnouncementForm(CleanSummer, forms.ModelForm):
    """
    Form to create announcement by AAC
    """
    text = forms.CharField(
        widget=SummernoteWidget(attrs={'style': 'width:750px'}),
        label="Announcement")
    summer_max_length = 2000

    class Meta:
        """
        Defines the model type, widgets, and fields for use by the ModelForm superclass to build the form
        """
        model = Announcement
        widgets = {
            'expiration': forms.SelectDateWidget(),
        }
        fields = ['text', 'expiration']
Beispiel #19
0
class BasicForm(forms.Form):
    title = forms.CharField(max_length=200)
    project = forms.ModelChoiceField(queryset=Board.objects.filter(activated=True))
    article_text = forms.CharField(widget=SummernoteWidget())

    def __init__(self, *args, **kwargs):
        # Get 'initial' argument if any
        initial_arguments = kwargs.get('initial', None)
        updated_initial = {}
        if initial_arguments:
            updated_initial['title'] = initial_arguments.get('title', None)
            updated_initial['article_text'] = initial_arguments.get('article_text', None)
        # You can also initialize form fields with hardcoded values
        # or perform complex DB logic here to then perform initialization
        updated_initial['comment'] = 'Please provide a comment'
        # Finally update the kwargs initial reference
        kwargs.update(initial=updated_initial)
        super(BasicForm, self).__init__(*args, **kwargs)
Beispiel #20
0
class ClassicNoteForm(forms.ModelForm):
    ac_time = forms.DateTimeField(label='AC时间',
                                  initial="",
                                  required=False,
                                  widget=DateTimeWidget(
                                      usel10n=True,
                                      bootstrap_version=3,
                                      attrs={'width': '100%'}))
    SCORE_CHOICE = zip(range(1, 11), range(1, 11))
    difficulty = forms.TypedChoiceField(choices=SCORE_CHOICE,
                                        label='难度系数',
                                        coerce=int)
    content = forms.CharField(label='笔记内容',
                              widget=SummernoteWidget(attrs={'width': '100%'}))

    def clean(self):
        cleaned_data = super(ClassicNoteForm, self).clean()
        ac_time = cleaned_data.get('ac_time')
        content = cleaned_data.get('content')
        difficulty = cleaned_data.get('difficulty')
        if ac_time:
            if ac_time >= now():
                msg = "AC time is invalid!"
                self.errors['ac_time'] = self.error_class([msg])
        if not content:
            msg = "Content should not be empty!"
            self.errors['content'] = self.error_class([msg])
        if not difficulty or difficulty < 1 or difficulty > 10:
            msg = "难度值的范围需要在[1,10]区间内!"
            self.errors['difficulty'] = self.error_class([msg])
        return cleaned_data

    class Meta:
        widgets = {
            'tags':
            autocomplete.ModelSelect2Multiple(url='note-tag-autocomplete')
        }
        labels = {
            'tags': '标签',
        }
        model = ClassicNote
        fields = '__all__'

        exclude = ['problem', 'author']
Beispiel #21
0
class SampleForm(forms.Form):
    desc1 = forms.CharField(label='iframe', widget=SummernoteWidget())
    desc2 = forms.CharField(label='inplace',
                            widget=SummernoteInplaceWidget(),
                            required=False)
    desc3 = forms.CharField(
        label='normal field',
        widget=forms.Textarea,
    )

    def clean(self):
        data = super().clean()

        if 'summer' not in data.get('desc1', ''):
            self.add_error('desc1', 'You have to put ‘summer’ in desc1')
            self.fields['desc1'].widget.attrs.update({'class': 'invalid'})
        if 'note' not in data.get('desc2', ''):
            self.add_error('desc2', 'You have to put ‘note’ in desc2')
            self.fields['desc2'].widget.attrs.update({'class': 'invalid'})
Beispiel #22
0
 class Meta():
     # main_image=forms.HiddenInput()
     model = Post
     fields = ("title", "post_heading", "text", "cartegory")
     widgets = {
         "title":
         forms.TextInput(attrs={
             "class": "form-control",
             "placeholder": "title of your post"
         }),
         "post_heading":
         forms.TextInput(
             attrs={
                 "class": "form-control",
                 "placeholder": "provide any suitable heading for your post"
             }),
         'text':
         SummernoteWidget()
     }
Beispiel #23
0
    def __init__(self, *args, **kwargs):
        key_type = kwargs.pop('key_type', None)
        value = kwargs.pop('value', None)
        super(EditKey, self).__init__(*args, **kwargs)

        if key_type == 'rich-text':
            self.fields['value'].widget = SummernoteWidget()
        elif key_type == 'boolean':
            self.fields['value'].widget = forms.CheckboxInput()
        elif key_type == 'integer':
            self.fields['value'].widget = forms.TextInput(attrs={'type': 'number'})
        elif key_type == 'file' or key_type == 'journalthumb':
            self.fields['value'].widget = forms.FileInput()
        elif key_type == 'text':
            self.fields['value'].widget = forms.Textarea()
        else:
            self.fields['value'].widget.attrs['size'] = '100%'

        self.fields['value'].initial = value
Beispiel #24
0
    class Meta:
        """Meta for ModelForm"""

        model = Paper
        fields = (
            'title',
            'content',
            'files',
            'approver',
            'support_names',
            'notify_names',
        )
        widgets = {
            'title':
            forms.TextInput(attrs={'placeholder': _('Enter title here.')}),
            'content': SummernoteWidget(),
            'files': forms.ClearableFileInput(attrs={'multiple': True}),
            'approver': forms.TextInput(),
        }
    class Meta:
        model = CommentForTodo
        fields = ('title', 'file_name', 'text')

        widgets = {
            'title':
            forms.TextInput(attrs={'size': 65}),
            'file_name':
            forms.TextInput(attrs={'size': 65}),
            'text':
            SummernoteWidget(
                attrs={
                    'summernote': {
                        'width': '100%',
                        'iframe': False,
                        "dialogsInBody": False
                    }
                }),
        }
Beispiel #26
0
class TestMailForm(forms.Form):
    subject = forms.CharField()
    from_name = forms.CharField(initial="John Doe")
    from_email = forms.CharField()
    to = forms.EmailField()
    body = forms.CharField(widget=SummernoteWidget())
    reply_to = forms.CharField(required=False)

    def send_mail(self):
        f = self.cleaned_data
        subject = f["subject"]
        from_email = '"{name}" <{email}>'.format(name=f["from_name"],
                                                 email=f["from_email"])
        to = [f["to"]]
        body = f["body"]
        reply_to = f["reply_to"]
        if not reply_to:
            reply_to = None

        send_mail(subject, body, from_email, to, reply_to=reply_to)
Beispiel #27
0
class ArticleForm(forms.Form):
    '''
    博文表单
    '''
    title = forms.CharField(initial='',
                            min_length=8,
                            label='标题',
                            strip=True,
                            error_messages={
                                'required': '不得为空',
                                'min_length': '不得少于8个字符'
                            })
    content = forms.CharField(initial='',
                              label='内容',
                              strip=True,
                              widget=SummernoteWidget())

    category = forms.ModelMultipleChoiceField(queryset=Category.objects.all())
    is_top = forms.BooleanField()
    is_discuss = forms.BooleanField()
Beispiel #28
0
 class Meta:
     model = models.Post
     fields = (
         'title',
         'text',
         'image',
     )
     widgets = {
         'title':
         forms.TextInput(attrs={
             'placeholder': 'Введите название статьи',
         }),
         'text':
         SummernoteWidget(),
         'image':
         forms.FileInput(attrs={
             'onchange': 'loadFile(event)',
             'id': 'imageId',
         })
     }
Beispiel #29
0
 class Meta:
     model = Course
     fields = (
         'name',
         'image',
         'annotation',
         'text',
         'lectures_number',
         'start',
         'end',
     )
     widgets = {
         'name': forms.TextInput(attrs={'class': 'form-control'}),
         'image': forms.ClearableFileInput(attrs={'class': 'form-control-file'}),
         'annotation': forms.Textarea(attrs={'class': 'form-control'}),
         'text': SummernoteWidget(attrs={'class': 'form-control'}),
         'lectures_number': forms.NumberInput(attrs={'class': 'form-control'}),
         'start': datepicker.DateTimePickerInput(format='%Y-%m-%d %H:%M'),
         'end': datepicker.DateTimePickerInput(format='%Y-%m-%d %H:%M'),
     }
Beispiel #30
0
class LiveinterviewForm(forms.Form):
    try:
        fieldsQueryset = BaseCode.objects.filter(
            h_category__exact="001").filter(m_category__exact="001").values()
        tasktypesQueryset = BaseCode.objects.filter(
            h_category__exact="001").filter(m_category__exact="002").values()
        lifestyleQueryset = BaseCode.objects.filter(
            h_category__exact="001").filter(m_category__exact="003").values()

        fieldsTuple = []
        for field in fieldsQueryset:
            fieldsTuple.append((field['key'], field['val']))

        tasktypesTuple = []
        for tasktype in tasktypesQueryset:
            tasktypesTuple.append((tasktype['key'], tasktype['val']))

        lifestylesTuple = []
        for lifestyle in lifestyleQueryset:
            lifestylesTuple.append((lifestyle['key'], lifestyle['val']))

        currencies = BaseCode.objects.filter(h_category__exact="002").filter(
            m_category__exact="001").values('key', 'val')[1:3]
        currenciesTuple = []
        for currency in currencies:
            currenciesTuple.append((currency['key'], currency['val']))

        fields = forms.CharField(
            widget=forms.CheckboxSelectMultiple(choices=fieldsTuple), )
        tasktypes = forms.CharField(
            widget=forms.CheckboxSelectMultiple(choices=tasktypesTuple), )
        lifestyles = forms.CharField(
            widget=forms.CheckboxSelectMultiple(choices=lifestylesTuple), )
        title = forms.CharField(label="title", max_length=50)
        content = forms.CharField(label="content", widget=SummernoteWidget())

        currency = forms.CharField(
            widget=forms.Select(choices=currenciesTuple), )
        amount = forms.IntegerField()
    except Exception as ex:
        print('error occured :', ex)
Beispiel #31
0
class PositionForm(forms.ModelForm):
    description = forms.CharField(
        widget=SummernoteWidget(
            attrs={'summernote': {'width': '100%', 'height': '200px'}}
        ))

    class Meta:
        model = models.Positions
        fields = ('name', 'description', 'time')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['description'].label = ""
        self.fields['description'].widget.attrs['placeholder'] = "Position description..."
        self.fields['name'].label = ""
        self.fields['name'].widget.attrs['placeholder'] = "Position Title"
        self.fields['name'].widget.attrs['class'] = 'circle--input--h3'
        self.fields['time'].label = ""
        self.fields['time'].widget.attrs['placeholder'] = "Position time involvement..."
        self.fields['time'].widget.attrs['class'] = 'circle--input--h3'
        self.fields['time'].required = False
    class Meta:
        model = Restaurant
        fields = [
            'title', 'slug', 'image', 'description', 'city',
            'start_working_time', 'end_working_time'
        ]

        widgets = {
            'title':
            forms.TextInput(attrs={'class': 'form-control'}),
            'slug':
            forms.TextInput(attrs={'class': 'form-control'}),
            'description':
            SummernoteWidget(),
            'city':
            forms.TextInput(attrs={'class': 'form-control'}),
            'start_working_time':
            forms.TimeInput(attrs={'class': 'form-control'}, format='%H:%M'),
            'end_working_time':
            forms.TimeInput(attrs={'class': 'form-control'}, format='%H:%M'),
        }
Beispiel #33
0
 class Meta:
     model = Application
     fields = [
         'applicant', 'job', 'supervisor_approval', 'how_qualified',
         'how_interested', 'availability', 'availability_note'
     ]
     widgets = {
         'applicant': forms.HiddenInput(),
         'job': forms.HiddenInput(),
         'availability_note': SummernoteWidget()
     }
     labels = {
         'supervisor_approval': 'Supervisor Approval:',
         'availability': 'Availability Requirements:',
         'availability_note': 'Availability Notes:'
     }
     help_texts = {
         'supervisor_approval':
         "I have my graduate supervisor's or Professional Master's Degree Program Director's approval to TA up to a maximum of 12 hours/week.",
         'availability_note': 'This field is optional.'
     }