Ejemplo n.º 1
0
    def assert_list_case_plans(self, response, case):
        for case_plan_rel in TestCasePlan.objects.filter(case=case):
            plan = case_plan_rel.plan
            self.assertContains(
                response,
                '<a href="/plan/{0}/{1}">{0}</a>'.format(plan.pk, slugify(plan.name)),
                html=True)

            self.assertContains(
                response,
                '<a href="/plan/{}/{}">{}</a>'.format(plan.pk, slugify(plan.name), plan.name),
                html=True)
Ejemplo n.º 2
0
def slugify_raise_on_invalid(title, use_old_slugify=False):
    """
    use uuslug to generate a slug but if the title is incorrect (only special chars or slug is empty), an exception
    is raised.

    :param title: to be slugified title
    :type title: str
    :param use_old_slugify: use the function `slugify()` defined in zds.utils instead of the one in uuslug. Usefull \
    for retro-compatibility with the old article/tutorial module, SHOULD NOT be used for the new one !
    :type use_old_slugify: bool
    :raise InvalidSlugError: on incorrect slug
    :return: the slugified title
    :rtype: str
    """

    if not isinstance(title, str):
        raise InvalidSlugError('', source=title)
    if not use_old_slugify:
        slug = slugify(title)
    else:
        slug = old_slugify(title)

    if not check_slug(slug):
        raise InvalidSlugError(slug, source=title)

    return slug
Ejemplo n.º 3
0
    def form_valid(self, form):
        """
        Sobrescreve o metodo form_valid para salvar
        o slug field
        """
        event = form.save(commit=False)
        # seta o commit do formulario como false

        from uuslug import slugify
        # importa o slugfy

        event.slug = slugify(event.name)
        # adiciona no formulario talk
        # no atributo slug a chamada do metodo
        # slugify de acordo com o titulo
        # passado no formulario

        event.save()
        # salvar a o formulario

        super(EventCreateView, self).form_valid(form)
        # chama o metodo super

        # e retorna para a página de sucesso
        return HttpResponseRedirect(
            self.get_success_url()
        )
Ejemplo n.º 4
0
    def save(self, *args, **kwargs):
        """Override save method for custom functionality."""
        # Create unique slug
        if not self.pk:
            self.slug = slugify(self.name, instance=self)

        # Calculate planning pad url
        if not self.planning_pad_url:
            url = urljoin(settings.ETHERPAD_URL,
                          getattr(settings, 'ETHERPAD_PREFIX', '') + self.slug)
            self.planning_pad_url = url

        # Update action items
        if self.pk:
            current_event = Event.objects.get(id=self.pk)
            if current_event.owner != self.owner:
                model = ContentType.objects.get_for_model(self)
                action_items = ActionItem.objects.filter(content_type=model,
                                                         object_id=self.pk)
                action_items.update(user=self.owner)

        super(Event, self).save(*args, **kwargs)

        # Subscribe owner to event
        Attendance.objects.get_or_create(event=self, user=self.owner)
Ejemplo n.º 5
0
def get(request, plan_id, slug=None, template_name='plan/get.html'):
    '''Display the plan details.'''
    SUB_MODULE_NAME = 'plans'

    try:
        tp = TestPlan.objects.select_related().get(plan_id=plan_id)
        tp.latest_text = tp.latest_text()
    except ObjectDoesNotExist:
        raise Http404

    # redirect if has a cheated slug
    if slug != slugify(tp.name):
        return HttpResponsePermanentRedirect(tp.get_absolute_url())

    # Initial the case counter
    confirm_status_name = 'CONFIRMED'
    tp.run_case = tp.case.filter(case_status__name=confirm_status_name)
    tp.review_case = tp.case.exclude(case_status__name=confirm_status_name)

    context_data = {
        'module': MODULE_NAME,
        'sub_module': SUB_MODULE_NAME,
        'test_plan': tp,
        'xml_form': ImportCasesViaXMLForm(initial={'a': 'import_cases'}),
    }
    return render_to_response(template_name, context_data,
                              context_instance=RequestContext(request))
Ejemplo n.º 6
0
def get_page_file_path(obj, filename):
    if hasattr(obj, 'upload_dir'):
        extension = filename.split('.')[-1]
        filename = "%s.%s" % (slugify(obj.url), extension)
        return os.path.join(obj.upload_dir, filename)
    else:
        raise AttributeError("%s does not have 'upload_dir' attribute" % obj.__class__.__name__)
Ejemplo n.º 7
0
    def test_manager(self):
        s = "This is a test ---"
        r = slugify(s)
        self.assertEquals(r, "this-is-a-test")

        s = 'C\'est déjà l\'été.'
        r = slugify(s)
        self.assertEquals(r, "cest-deja-lete")

        s = 'Nín hǎo. Wǒ shì zhōng guó rén'
        r = slugify(s)
        self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

        s = '影師嗎'
        r = slugify(s)
        self.assertEquals(r, "ying-shi-ma")
Ejemplo n.º 8
0
    def form_valid(self, form):
        u"""
        Sobrescreve o metodo form_valid para buscar
        o palestrante/user através do request
        """
        talk = form.save(commit=False)
        # seta o commit do formulario como false

        from uuslug import slugify
        # importa o slugfy

        talk.slug = slugify(talk.title)
        # adiciona no formulario talk
        # no atributo slug a chamada do metodo
        # slugify de acordo com o titulo
        # passado no formulario

        talk.speaker = SpeakerUser.objects.get(
            username=self.request.user.username
        )
        # associa o palestrante de acordo
        # com uma pesquisa feito no model SpeakerUser
        # filtrando pelo usuario logado

        talk.save()
        # salvar a o formulario

        super(TalkUpdateView, self).form_valid(form)
Ejemplo n.º 9
0
Archivo: models.py Proyecto: koztay/stb
def image_upload_to_featured(instance, filename):
    title = instance.product.title
    if len(title) > 50:
        title = title[:50]
    slug = slugify(title)
    basename, file_extension = filename.split(".")
    new_filename = "%s-%s.%s" % (slug, instance.id, file_extension)
    return "products/%s/featured/%s" % (slug, new_filename)
Ejemplo n.º 10
0
 def save(self, *args, **kwargs):
     if self.pk is None:
         self.slug = slugify(self.title)
     try:
         super(ForumThread, self).save()
     except IntegrityError:
         self.slug += '-' + str(ForumThread.objects.filter(slug__startswith=self.slug).count())
         super(ForumThread, self).save()
Ejemplo n.º 11
0
def create_slug(sender, instance, raw, **kwargs):
    """Auto create unique slug and calculate planning_pad_url."""
    if not instance.slug:
        instance.slug = slugify(instance.name, instance=instance)

    if not instance.planning_pad_url:
        url = urljoin(settings.ETHERPAD_URL, getattr(settings, "ETHERPAD_PREFIX", "") + instance.slug)
        instance.planning_pad_url = url
Ejemplo n.º 12
0
    def save(self, **kwargs):
        if self.pk:
            self.modified_at = datetime.now()

        if not self.slug:
            self.slug = slugify(self.title, instance=self)

        super(Entry, self).save(**kwargs)
Ejemplo n.º 13
0
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Theme,self).save(*args,**kwargs)

        if os.path.exists(self.extracted_path):
            shutil.rmtree(self.extracted_path)
        os.makedirs(self.extracted_path)
        z = ZipFile(self.zipfile.file,'r')
        z.extractall(self.extracted_path)
Ejemplo n.º 14
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.article_title)
     try:
         curr_article = Article.objects.get(id=self.id)
         if curr_article.article_image != self.article_image:
             curr_article.article_image.delete(save=False)
     except ObjectDoesNotExist:
         pass
     super().save(*args, **kwargs)
Ejemplo n.º 15
0
def generate_unique_code(title):
    project_code = slugify(title)
    if Project.objects.filter(code=project_code).exists():
        match = re.match(r'/.*-another-(\d+)$/g', title)
        if match:
            project_code = generate_unique_code(title + '-another-' + match[1])
        else:
            project_code = generate_unique_code(title + '-another-1')
    return project_code
Ejemplo n.º 16
0
 def save(self, *args, **kwargs):
     from DjangoBlog.blog_signals import article_save_signal
     if not self.slug or self.slug == 'no-slug' or not self.id:
         slug = self.title if 'title' in self.__dict__ else self.name
         self.slug = slugify(slug)
     super().save(*args, **kwargs)
     # type = self.__class__.__name__
     is_update_views = 'update_fields' in kwargs and len(kwargs['update_fields']) == 1 and kwargs['update_fields'][
         0] == 'views'
     article_save_signal.send(sender=self.__class__, is_update_views=is_update_views, id=self.id)
Ejemplo n.º 17
0
def create_slug(instance, sender, new_slug=None):
    print(instance)
    slug = slugify(instance.title)
    if new_slug is not None:
        slug = new_slug
    qs = sender.objects.filter(slug=slug)
    exists = qs.exists()
    if exists:
        new_slug = "%s-%s" % (slug, qs.first().id)
        return create_slug(instance, sender=sender, new_slug=new_slug)
    return slug
Ejemplo n.º 18
0
    def save(self, commit=True):
        custom_part_type = super(NewCustomPartTypeForm, self).save(commit=False)

        slug = slugify(custom_part_type.name)
        custom_part_type.set_short_name(slug)
        
        custom_part_type.author = self._user

        if commit:
            custom_part_type.save()
            self.save_m2m()
        return custom_part_type
Ejemplo n.º 19
0
    def save(self, *args,  **kwargs):
        """
        Customiza o metodo salvar da classe
        para guardar o slug do palestrante
        """
        from uuslug import uuslug as slugify
        if not self.first_name:
            self.first_name = 'speaker noname'
        slug_str = "%s %s" % (self.first_name, self.last_name)

        self.slug = slugify(slug_str, instance=self, start_no=1)
        super(SpeakerUser, self).save(**kwargs)
Ejemplo n.º 20
0
 def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
     pinyin = slugify(self.product_category.category, max_length=100)
     code = ""
     for word in pinyin.split('-'):
         first_letter = word[0].upper()
         code += first_letter
     data_index = code + ''.join([choice('0123456789') for i in range(5)])
     while not Product.objects.filter(product_index=data_index).count() == 0:
         data_index = code + ''.join([choice('0123456789') for i in range(5)])
     if not self.product_index:
         self.product_index = data_index
     super(Product, self).save(force_insert, force_update, using, update_fields)
Ejemplo n.º 21
0
    def save(self, *args, **kwargs):
        NumbasObject.get_parsed_content(self)
        
        self.slug = slugify(self.name)

        if 'metadata' in self.parsed_content.data:
            licence_name = self.parsed_content.data['metadata'].get('licence',None)
        else:
            licence_name = None
        self.licence = Licence.objects.filter(name=licence_name).first()
            
        super(Exam, self).save(*args, **kwargs)
Ejemplo n.º 22
0
    def save(self):
	#super(Post, self).save()
	import time
	date = datetime.date.today()
	self.slug = "%i-%i-%i/%s-%i" % (
	    date.year, date.month, date.day, slugify(self.title), time.time()
	)
	#self.points = self.upvotes - self.downvotes
	if self.total_votes is None:
	    self.total_votes = 1
	self.scores = post_score(self)

	super(Post, self).save()
Ejemplo n.º 23
0
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        self.content_r = render_bbcode(self.content)

        if not self.slug:
            self.slug = slugify(self.title, instance=self)

        if self.pk:
            self.modified_at = datetime.now()
        else:
            self.created_at = datetime.now()

        super(Entry, self).save(
            force_insert, force_update, using, update_fields)
Ejemplo n.º 24
0
    def handle(self, *args, **options):
        _file = options['manifest_path']
        if os.path.isfile(_file) and _file[-5:] == '.json':
            with open(_file, 'r') as json_file:
                data = json_handler.load(json_file)
            _type = 'TUTORIAL'
            if data['type'].lower() == 'article':
                _type = 'ARTICLE'
            versioned = VersionedContent('', _type, data['title'], slugify(data['title']))
            versioned.description = data['description']
            if 'introduction' in data:
                versioned.introduction = data['introduction']
            if 'conclusion' in data:
                versioned.conclusion = data['conclusion']
            versioned.licence = Licence.objects.filter(code=data['licence']).first()
            versioned.version = '2.0'
            versioned.slug = slugify(data['title'])
            if 'parts' in data:
                # if it is a big tutorial
                for part in data['parts']:
                    current_part = Container(part['title'],
                                             str(part['pk']) + '_' + slugify(part['title']))
                    if 'introduction' in part:
                        current_part.introduction = part['introduction']
                    if 'conclusion' in part:
                        current_part.conclusion = part['conclusion']
                    versioned.add_container(current_part)
                    for chapter in part['chapters']:
                        current_chapter = Container(chapter['title'],
                                                    str(chapter['pk']) + '_' + slugify(chapter['title']))
                        if 'introduction' in chapter:
                            current_chapter.introduction = chapter['introduction']
                        if 'conclusion' in chapter:
                            current_chapter.conclusion = chapter['conclusion']
                        current_part.add_container(current_chapter)
                        for extract in chapter['extracts']:
                            current_extract = Extract(extract['title'],
                                                      str(extract['pk']) + '_' + slugify(extract['title']))
                            current_chapter.add_extract(current_extract)
                            current_extract.text = current_extract.get_path(True)

            elif 'chapter' in data:
                # if it is a mini tutorial
                for extract in data['chapter']['extracts']:
                    current_extract = Extract(extract['title'],
                                              str(extract['pk']) + '_' + slugify(extract['title']))
                    versioned.add_extract(current_extract)
                    current_extract.text = current_extract.get_path(True)

            elif versioned.type == 'ARTICLE':
                extract = Extract('text', 'text')
                versioned.add_extract(extract)
                extract.text = extract.get_path(True)

            with open(_file, 'w') as json_file:
                json_file.write(versioned.get_json())
Ejemplo n.º 25
0
    def save(self, *args, **kwargs):
        NumbasObject.get_parsed_content(self)

        self.slug = slugify(self.name)

        if 'metadata' in self.parsed_content.data:
            licence_name = self.parsed_content.data['metadata'].get('licence',None)
        else:
            licence_name = None
        self.licence = Licence.objects.filter(name=licence_name).first()

        super(Question, self).save(*args, **kwargs)

        if 'tags' in self.parsed_content.data:
            self.tags.set(*[t.strip() for t in self.parsed_content.data['tags']])
Ejemplo n.º 26
0
    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Extension,self).save(*args,**kwargs)

        if self.zipfile:
            if os.path.exists(self.extracted_path):
                shutil.rmtree(self.extracted_path)
            os.makedirs(self.extracted_path)

            name,extension = os.path.splitext(self.zipfile.name)
            if extension.lower() == '.zip':
                z = ZipFile(self.zipfile.file,'r')
                z.extractall(self.extracted_path)
            elif extension.lower() == '.js':
                file = open(os.path.join(self.extracted_path,self.location+'.js'),'w')
                file.write(self.zipfile.file.read())
                file.close()
Ejemplo n.º 27
0
    def form_valid(self, form):
        """
        Sobrescreve o metodo form_valid para buscar
        o palestrante/user através do request
        """
        context = self.get_context_data()
        mediatalk_forms = context['mediatalk_formset']

        talk = form.save(commit=False)
        # seta o commit do formulario como false

        from uuslug import slugify
        # importa o slugfy

        talk.slug = slugify(talk.title)
        # adiciona no formulario talk
        # no atributo slug a chamada do metodo
        # slugify de acordo com o titulo
        # passado no formulario

        talk.speaker = SpeakerUser.objects.get(
            username=self.request.user.username
        )
        # associa o palestrante de acordo
        # com uma pesquisa feito no model SpeakerUser
        # filtrando pelo usuario logado
        talk.save()
        super(TalkCreateView, self).form_valid(form)
        # chama o metodo super

        # salvar as medias no formulario
        if mediatalk_forms.is_valid():
            for idx, media in enumerate(mediatalk_forms):
                media_type, media_title, media_url = self.get_media_form_data(
                    media,
                    idx
                )
                if media_type and media_title and media_url:
                    media.save(commit=False)
                    media.instance.talk = talk
                    media.save()

        # e retorna para a página de sucesso
        return HttpResponseRedirect(
            self.get_success_url()
        )
Ejemplo n.º 28
0
    def pre_save(self, instance, add):
        default = super(AutoSlugField, self).pre_save(instance, add)

        if default or not add or not self.populate_from:
            return default

        value = getattr(instance, self.populate_from)

        if value is None:
            return default

        # slug = slugify(smart_text(value))[:self.max_length].strip('-')
        slug = slugify(value, max_length=23, word_boundary=True)

        # Update the model’s attribute
        setattr(instance, self.attname, slug)

        return slug
Ejemplo n.º 29
0
    def save(self, *args, **kwargs):
        """Override save method for custom functionality."""
        # Create unique slug
        if not self.pk:
            self.slug = slugify(self.name, instance=self)

        # Update action items
        if self.pk:
            current_event = Event.objects.get(id=self.pk)
            if current_event.owner != self.owner:
                model = ContentType.objects.get_for_model(self)
                action_items = ActionItem.objects.filter(content_type=model, object_id=self.pk)
                action_items.update(user=self.owner)

        super(Event, self).save(*args, **kwargs)

        # Subscribe owner to event
        Attendance.objects.get_or_create(event=self, user=self.owner)
Ejemplo n.º 30
0
 def test_method_save_speaker(self):
     u"""
     Testa e o metodo save esta salvando o slug
     do palestrante de acordo com o primeiro
     nome e segundo nome
     """
     self.speaker.first_name = u'Ashely'
     self.speaker.last_name = u' Cole Jr'
     self.speaker.save()
     from uuslug import slugify
     slug_str = "%s %s" % (
         self.speaker.first_name,
         self.speaker.last_name
     )
     slug = slugify(slug_str)
     self.assertEqual(
         self.speaker.slug,
         slug
     )
Ejemplo n.º 31
0
 def get(self, request, *args, **kwargs):
     test_plan = self.get_object()
     return HttpResponsePermanentRedirect(
         reverse('test_plan_url',
                 args=[test_plan.pk, slugify(test_plan.name)]))
Ejemplo n.º 32
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.summary, instance=self)
     super(Task, self).save(*args, **kwargs)
Ejemplo n.º 33
0
 def save(self, *args, **kwargs):
     self.url = slugify(self.name)
     super(people, self).save(*args, **kwargs)
Ejemplo n.º 34
0
    def handle(self, *args, **options):
        _file = options['manifest_path']
        if os.path.isfile(_file) and _file[-5:] == '.json':
            with open(_file, 'r') as json_file:
                data = json_reader.load(json_file)
            _type = 'TUTORIAL'
            if data['type'].lower() == 'article':
                _type = 'ARTICLE'
            versioned = VersionedContent('', _type, data['title'],
                                         slugify(data['title']))
            versioned.description = data['description']
            if 'introduction' in data:
                versioned.introduction = data['introduction']
            if 'conclusion' in data:
                versioned.conclusion = data['conclusion']
            versioned.licence = Licence.objects.filter(
                code=data['licence']).first()
            versioned.version = '2.0'
            versioned.slug = slugify(data['title'])
            if 'parts' in data:
                # if it is a big tutorial
                for part in data['parts']:
                    current_part = Container(
                        part['title'],
                        str(part['pk']) + '_' + slugify(part['title']))
                    if 'introduction' in part:
                        current_part.introduction = part['introduction']
                    if 'conclusion' in part:
                        current_part.conclusion = part['conclusion']
                    versioned.add_container(current_part)
                    for chapter in part['chapters']:
                        current_chapter = Container(
                            chapter['title'],
                            str(chapter['pk']) + '_' +
                            slugify(chapter['title']))
                        if 'introduction' in chapter:
                            current_chapter.introduction = chapter[
                                'introduction']
                        if 'conclusion' in chapter:
                            current_chapter.conclusion = chapter['conclusion']
                        current_part.add_container(current_chapter)
                        for extract in chapter['extracts']:
                            current_extract = Extract(
                                extract['title'],
                                str(extract['pk']) + '_' +
                                slugify(extract['title']))
                            current_chapter.add_extract(current_extract)
                            current_extract.text = current_extract.get_path(
                                True)

            elif 'chapter' in data:
                # if it is a mini tutorial
                for extract in data['chapter']['extracts']:
                    current_extract = Extract(
                        extract['title'],
                        str(extract['pk']) + '_' + slugify(extract['title']))
                    versioned.add_extract(current_extract)
                    current_extract.text = current_extract.get_path(True)

            elif versioned.type == 'ARTICLE':
                extract = Extract('text', 'text')
                versioned.add_extract(extract)
                extract.text = extract.get_path(True)

            with open(_file, 'w') as json_file:
                json_file.write(versioned.get_json())
Ejemplo n.º 35
0
	def save(self, *args, **kwargs):

		self.cpu_slug = '{}'.format(slugify(self.title))	

		super(Manufacturer, self).save(*args, **kwargs)
Ejemplo n.º 36
0
    def post(self, request):
        """
        创建文章
        """

        content = request.data.get('content')
        title = request.data.get('title')
        tags = request.data.get('tags')
        groups = request.data.get('groups')
        access_status = request.data.get('access_status')
        password = request.data.get('password')
        show_comment = request.data.get('show_comment')
        allow_comment = request.data.get('allow_comment')

        banner = request.data.get('banner')
        if not all([banner]):
            banner = self.tools.get_random_banner()
        if not all([title]):
            return request.response.FAILED(msg='创建文章失败,标题不能为空')
        else:
            if models.Article.objects.filter(
                    Q(title=title) | Q(slug=slugify(title))):
                return request.response.FAILED(msg='创建文章失败,标题已存在')

            if show_comment in self.COMMENT_STATUS and allow_comment in self.COMMENT_STATUS:
                show_comment = self.tools.try_safe_eval(show_comment)
                allow_comment = self.tools.try_safe_eval(allow_comment)
                assert isinstance(show_comment, bool) and isinstance(
                    allow_comment, bool), '评论状态异常'
            else:
                return request.response(response_code=400)

            try:
                access_status = int(access_status)
                if access_status not in models.Article.ACCESS_STATUS_DICT:
                    return request.response(response_code=400)
            except:
                return request.response(response_code=400)
            else:
                if access_status == 2:
                    if not all([password]):
                        return request.response.FAILED(
                            msg='创建文章失败,可见性设置为密码访问时,密码不能为空哦~')
                else:
                    password = None

        article_id = shortuuid.uuid()
        article_info = models.Article.objects.create(
            id=article_id,
            title=title,
            show_comment=show_comment,
            allow_comment=allow_comment,
            access_status=access_status,
            password=password,
            banner=banner,
            content=content)

        if tags:
            article_info.set_tag(tag_name=self.tools.try_safe_eval(tags))
        if groups:
            article_info.set_group(group_name=self.tools.try_safe_eval(groups))

        return request.response.SUCCESS(msg='文章创建成功',
                                        article_id=article_id,
                                        redirect=reverse(
                                            'edit_article',
                                            kwargs={'article_id': article_id}))
Ejemplo n.º 37
0
 def save(self):
     self.slug = '{0}'.format(slugify(
         self.name))  # Статья будет отображаться в виде NN-АА-АААА
     super(Subcategory, self).save()
Ejemplo n.º 38
0
def get_image_filename(instance, filename):
    country = slugify(
        get_object_or_404(CountryGuidePost, country=instance.country).country)
    return "country_guide/slideshow/%s/%s" % (country, filename)
Ejemplo n.º 39
0
	def save(self, *args, **kwargs):

		self.cpu_slug = '{}'.format(slugify(self.title))	

		super(Good, self).save(*args, **kwargs)
Ejemplo n.º 40
0
def edit(request, plan_id, template_name='plan/edit.html'):
    """Edit test plan view"""

    try:
        test_plan = TestPlan.objects.select_related().get(plan_id=plan_id)
    except ObjectDoesNotExist:
        raise Http404

    # If the form is submitted
    if request.method == "POST":
        form = EditPlanForm(request.POST)
        form.populate(product_id=request.POST.get('product'))

        # FIXME: Error handle
        if form.is_valid():
            if request.user.has_perm('testplans.change_testplan'):
                test_plan.name = form.cleaned_data['name']
                test_plan.parent = form.cleaned_data['parent']
                test_plan.product = form.cleaned_data['product']
                test_plan.product_version = form.cleaned_data[
                    'product_version']
                test_plan.type = form.cleaned_data['type']
                test_plan.is_active = form.cleaned_data['is_active']
                test_plan.extra_link = form.cleaned_data['extra_link']
                test_plan.owner = form.cleaned_data['owner']
                # IMPORTANT! tp.current_user is an instance attribute,
                # added so that in post_save, current logged-in user info
                # can be accessed.
                # Instance attribute is usually not a desirable solution.
                test_plan.current_user = request.user
                test_plan.text = form.cleaned_data['text']
                test_plan.save()

            # Update plan email settings
            update_plan_email_settings(test_plan, form)
            return HttpResponseRedirect(
                reverse('test_plan_url',
                        args=[plan_id, slugify(test_plan.name)]))
    else:
        form = EditPlanForm(
            initial={
                'name': test_plan.name,
                'product': test_plan.product_id,
                'product_version': test_plan.product_version_id,
                'type': test_plan.type_id,
                'text': test_plan.text,
                'parent': test_plan.parent_id,
                'is_active': test_plan.is_active,
                'extra_link': test_plan.extra_link,
                'owner': test_plan.owner,
                'auto_to_plan_owner': test_plan.emailing.auto_to_plan_owner,
                'auto_to_plan_author': test_plan.emailing.auto_to_plan_author,
                'auto_to_case_owner': test_plan.emailing.auto_to_case_owner,
                'auto_to_case_default_tester':
                test_plan.emailing.auto_to_case_default_tester,
                'notify_on_plan_update':
                test_plan.emailing.notify_on_plan_update,
                'notify_on_case_update':
                test_plan.emailing.notify_on_case_update,
            })
        form.populate(product_id=test_plan.product_id)

    context_data = {
        'test_plan': test_plan,
        'form': form,
    }
    return render(request, template_name, context_data)
Ejemplo n.º 41
0
 def save(self, *args, **kwargs):
     self.url_slug = slugify(self.title)
     super(Articles, self).save(*args, **kwargs)
Ejemplo n.º 42
0
 def save(self):
     self.slug = slugify(self.name)
     super().save()
Ejemplo n.º 43
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.name)
     super().save(*args, **kwargs)
Ejemplo n.º 44
0
 def save(self, *args, **kwargs):
     if not self.slug:
         self.slug = slugify(self.title)
     super().save(*args, **kwargs)
Ejemplo n.º 45
0
 def save(self, *args, **kwargs):
     # Create unique slug
     if not self.slug:
         self.slug = slugify(self.name, instance=self)
     super(FunctionalArea, self).save(*args, **kwargs)
 def save(self, *args, **kwargs):
     if not self.slug:
         #self.slug = slugify(self.title, allow_unicode=True)
         self.slug = slugify(self.title)
     super(Post, self).save(*args, **kwargs)
Ejemplo n.º 47
0
    def put(self, request, article_id):
        content = request.data.get('content')
        title = request.data.get('title')
        tags = request.data.get('tags')
        groups = request.data.get('groups')
        access_status = request.data.get('access_status')
        password = request.data.get('password')
        show_comment = request.data.get('show_comment')
        allow_comment = request.data.get('allow_comment')

        banner = request.data.get('banner')

        article_info = get_object_or_404(models.Article, pk=article_id)

        if not all([banner]):
            banner = self.tools.get_random_banner()
        if not all([title]):
            return request.response.FAILED(msg='更新文章失败,标题不能为空')
        else:
            if models.Article.objects.filter(
                    ~Q(id=article_id), **{
                        'title': title,
                        'slug': slugify(title)
                    }):
                return request.response.FAILED(msg='更新文章失败,标题与其他已存在文章重复')
            if show_comment in Article.COMMENT_STATUS and allow_comment in Article.COMMENT_STATUS:
                show_comment = self.tools.try_safe_eval(show_comment)
                allow_comment = self.tools.try_safe_eval(allow_comment)
                assert isinstance(show_comment, bool) and isinstance(
                    allow_comment, bool), '评论状态异常'
            else:
                return request.response(response_code=400)

            try:
                access_status = int(access_status)
                if access_status not in models.Article.ACCESS_STATUS_DICT:
                    return request.response(response_code=400)
            except:
                return request.response(response_code=400)
            else:
                if access_status == 2:
                    if not all([password]):
                        return request.response.FAILED(
                            msg='更新文章失败,可见性设置为密码访问时,密码不能为空哦~')
                else:
                    password = None

        models.Article.objects.filter(id=article_id).update(
            title=title,
            show_comment=show_comment,
            allow_comment=allow_comment,
            access_status=access_status,
            password=password,
            banner=banner,
            content=content)

        if tags:
            article_info.set_tag(tag_name=self.tools.try_safe_eval(tags))
        if groups:
            article_info.set_group(group_name=self.tools.try_safe_eval(groups))

        return request.response.SUCCESS(msg='文章更新成功')
Ejemplo n.º 48
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.name)
     super(Category, self).save(*args, **kwargs)
Ejemplo n.º 49
0
 def save(self, *args, **kwargs):
     # Create unique slug
     if not self.slug:
         self.slug = slugify(self.name, instance=self)
     super(EventGoal, self).save(*args, **kwargs)
Ejemplo n.º 50
0
 def get_absolute_url(self):
     return reverse('plan-get',
                    kwargs={
                        'plan_id': self.plan_id,
                        'slug': slugify(self.name),
                    })
Ejemplo n.º 51
0
 def _get_absolute_url(self):
     return reverse('test_plan_url', args=[self.pk, slugify(self.name)])
Ejemplo n.º 52
0
def edit(request, plan_id, template_name='plan/edit.html'):
    """Edit test plan view"""

    try:
        test_plan = TestPlan.objects.select_related().get(plan_id=plan_id)
    except ObjectDoesNotExist:
        raise Http404

    # If the form is submitted
    if request.method == "POST":
        form = EditPlanForm(request.POST, request.FILES)
        if request.POST.get('product'):
            form.populate(product_id=request.POST['product'])
        else:
            form.populate()

        # FIXME: Error handle
        if form.is_valid():
            if request.user.has_perm('testplans.change_testplan'):
                test_plan.name = form.cleaned_data['name']
                test_plan.parent = form.cleaned_data['parent']
                test_plan.product = form.cleaned_data['product']
                test_plan.product_version = form.cleaned_data[
                    'product_version']
                test_plan.type = form.cleaned_data['type']
                test_plan.is_active = form.cleaned_data['is_active']
                test_plan.extra_link = form.cleaned_data['extra_link']
                test_plan.owner = form.cleaned_data['owner']
                # IMPORTANT! tp.current_user is an instance attribute,
                # added so that in post_save, current logged-in user info
                # can be accessed.
                # Instance attribute is usually not a desirable solution.
                test_plan.current_user = request.user
                test_plan.save()

            if request.user.has_perm('testplans.add_testplantext'):
                new_text = form.cleaned_data['text']
                text_checksum = checksum(new_text)

                if not test_plan.text_exist(
                ) or text_checksum != test_plan.text_checksum():
                    test_plan.add_text(author=request.user,
                                       plan_text=new_text,
                                       text_checksum=text_checksum)

            if request.user.has_perm('testplans.change_envplanmap'):
                test_plan.clear_env_groups()

                if request.POST.get('env_group'):
                    env_groups = EnvGroup.objects.filter(
                        id__in=request.POST.getlist('env_group'))

                    for env_group in env_groups:
                        test_plan.add_env_group(env_group=env_group)
            # Update plan email settings
            update_plan_email_settings(test_plan, form)
            return HttpResponseRedirect(
                reverse('test_plan_url',
                        args=[plan_id, slugify(test_plan.name)]))
    else:
        # Generate a blank form
        # Temporary use one environment group in this case
        if test_plan.env_group.all():
            for env_group in test_plan.env_group.all():
                env_group_id = env_group.id
                break
        else:
            env_group_id = None

        form = EditPlanForm(
            initial={
                'name':
                test_plan.name,
                'product':
                test_plan.product_id,
                'product_version':
                test_plan.product_version_id,
                'type':
                test_plan.type_id,
                'text':
                test_plan.latest_text() and test_plan.latest_text().plan_text
                or '',
                'parent':
                test_plan.parent_id,
                'env_group':
                env_group_id,
                'is_active':
                test_plan.is_active,
                'extra_link':
                test_plan.extra_link,
                'owner':
                test_plan.owner,
                'auto_to_plan_owner':
                test_plan.emailing.auto_to_plan_owner,
                'auto_to_plan_author':
                test_plan.emailing.auto_to_plan_author,
                'auto_to_case_owner':
                test_plan.emailing.auto_to_case_owner,
                'auto_to_case_default_tester':
                test_plan.emailing.auto_to_case_default_tester,
                'notify_on_plan_update':
                test_plan.emailing.notify_on_plan_update,
                'notify_on_case_update':
                test_plan.emailing.notify_on_case_update,
            })
        form.populate(product_id=test_plan.product_id)

    context_data = {
        'test_plan': test_plan,
        'form': form,
    }
    return render(request, template_name, context_data)
Ejemplo n.º 53
0
 def get_absolute_url(self):
     return ('test_plan_url', (), {
         'plan_id': self.plan_id,
         'slug': slugify(self.name),
     })
Ejemplo n.º 54
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.name)
     # self.article_number = Article.objects.filter(category=self).count()
     super().save(*args, **kwargs)
Ejemplo n.º 55
0
 def save(self, *args, **kwargs):
     if not self.slug:
         self.slug = slugify(self.name)
     super(Note, self).save(*args, **kwargs)
Ejemplo n.º 56
0
 def save(self, *args, **kwargs):
     """
     **uid**: :code:`{levelcode}`
     """
     self.slug = slugify(self.name)
     super(DivisionLevel, self).save(*args, **kwargs)
Ejemplo n.º 57
0
    def test_manager(self):

        txt = "This is a test ---"
        r = slugify(txt)
        self.assertEqual(r, "this-is-a-test")

        txt = "This -- is a ## test ---"
        r = slugify(txt)
        self.assertEqual(r, "this-is-a-test")

        txt = '影師嗎'
        r = slugify(txt)
        self.assertEqual(r, "ying-shi-ma")

        txt = 'C\'est déjà l\'été.'
        r = slugify(txt)
        self.assertEqual(r, "c-est-deja-l-ete")

        txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
        r = slugify(txt)
        self.assertEqual(r, "nin-hao-wo-shi-zhong-guo-ren")

        txt = 'Компьютер'
        r = slugify(txt)
        self.assertEqual(r, "kompiuter")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt)
        self.assertEqual(r, "jaja-lol-mememeoo-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=9)
        self.assertEqual(r, "jaja-lol")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=15)
        self.assertEqual(r, "jaja-lol-mememe")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=50)
        self.assertEqual(r, "jaja-lol-mememeoo-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=15, word_boundary=True)
        self.assertEqual(r, "jaja-lol-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=17, word_boundary=True)
        self.assertEqual(r, "jaja-lol-mememeoo")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=18, word_boundary=True)
        self.assertEqual(r, "jaja-lol-mememeoo")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=19, word_boundary=True)
        self.assertEqual(r, "jaja-lol-mememeoo-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=20, word_boundary=True, separator=".")
        self.assertEqual(r, "jaja.lol.mememeoo.a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=20, word_boundary=True, separator="ZZZZZZ")
        self.assertEqual(r, "jajaZZZZZZlolZZZZZZmememeooZZZZZZa")

        txt = "___This is a test ---"
        r = slugify(txt)
        self.assertEqual(r, "this-is-a-test")

        txt = "___This is a test___"
        r = slugify(txt)
        self.assertEqual(r, "this-is-a-test")

        txt = 'one two three four five'
        r = slugify(txt, max_length=13, word_boundary=True, save_order=True)
        self.assertEqual(r, "one-two-three")

        txt = 'one two three four five'
        r = slugify(txt, max_length=13, word_boundary=True, save_order=False)
        self.assertEqual(r, "one-two-three")

        txt = 'one two three four five'
        r = slugify(txt, max_length=12, word_boundary=True, save_order=False)
        self.assertEqual(r, "one-two-four")

        txt = 'one two three four five'
        r = slugify(txt, max_length=12, word_boundary=True, save_order=True)
        self.assertEqual(r, "one-two")

        txt = 'this has a stopword'
        r = slugify(txt, stopwords=['stopword'])
        self.assertEqual(r, 'this-has-a')

        txt = 'the quick brown fox jumps over the lazy dog'
        r = slugify(txt, stopwords=['the'])
        self.assertEqual(r, 'quick-brown-fox-jumps-over-lazy-dog')

        txt = 'Foo A FOO B foo C'
        r = slugify(txt, stopwords=['foo'])
        self.assertEqual(r, 'a-b-c')

        txt = 'Foo A FOO B foo C'
        r = slugify(txt, stopwords=['FOO'])
        self.assertEqual(r, 'a-b-c')

        txt = 'the quick brown fox jumps over the lazy dog in a hurry'
        r = slugify(txt, stopwords=['the', 'in', 'a', 'hurry'])
        self.assertEqual(r, 'quick-brown-fox-jumps-over-lazy-dog')
Ejemplo n.º 58
0
 def save(self, **kwargs):
     self.slug = slugify(self.title)
     super().save(**kwargs)
Ejemplo n.º 59
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.title)
     super(Post, self).save(*args, **kwargs)
Ejemplo n.º 60
0
    def test_manager(self):

        txt = "This is a test ---"
        r = slugify(txt)
        self.assertEqual(r, "this-is-a-test")

        txt = "This -- is a ## test ---"
        r = slugify(txt)
        self.assertEqual(r, "this-is-a-test")

        txt = 'C\'est déjà l\'été.'
        r = slugify(txt)
        self.assertEqual(r, "cest-deja-lete")

        txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
        r = slugify(txt)
        self.assertEqual(r, "nin-hao-wo-shi-zhong-guo-ren")

        txt = 'Компьютер'
        r = slugify(txt)
        self.assertEqual(r, "kompiuter")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt)
        self.assertEqual(r, "jaja-lol-mememeoo-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=9)
        self.assertEqual(r, "jaja-lol")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=15)
        self.assertEqual(r, "jaja-lol-mememe")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=50)
        self.assertEqual(r, "jaja-lol-mememeoo-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=15, word_boundary=True)
        self.assertEqual(r, "jaja-lol-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=19, word_boundary=True)
        self.assertEqual(r, "jaja-lol-mememeoo")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=20, word_boundary=True)
        self.assertEqual(r, "jaja-lol-mememeoo-a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=20, word_boundary=True, separator=".")
        self.assertEqual(r, "jaja.lol.mememeoo.a")

        txt = 'jaja---lol-méméméoo--a'
        r = slugify(txt, max_length=20, word_boundary=True, separator="ZZZZZZ")
        self.assertEqual(r, "jajaZZZZZZlolZZZZZZmememeooZZZZZZa")