Exemplo n.º 1
0
def add_link(request):
    import pdb; pdb.set_trace()
    context = RequestContext(request)
    if request.method == 'POST':
        url = request.POST.get("url", "")
        tags = request.POST.get("tags", "")
        title = request.POST.get("title", "")

        # create the link object
        link = Link.objects.create(title=title, url=url)
        link.save()

        # add tags
        tags = tags.split()
        # remove duplicates
        tags = list(set(tags))
        for tag in tags:
            # check whether a tag with this name already exists
            if Tag.objects.filter(name=tag).count() > 0:
                # user the preexisting tags
                new_tag = Tag.objects.get(name=tag)
                link.tags.add(new_tag)
            else:
                # otherwise create the tag
                new_tag = Tag(name=tag)
                new_tag.save()
                link.tags.add(new_tag)
    return redirect(index)
Exemplo n.º 2
0
def add_link(request):
    """Add a new link"""

    # Get the context
    context = RequestContext(request)
    if request.method == "POST":
        url = request.POST.get("url", "")
        tags = request.POST.get("tags", "")
        title = request.POST.get("title", "")

        # TODO: Add the link to the tags
        try:
            link = Link(title=title, url=url)
            link.save()
        except IntegrityError:
            messages.add_message(request, messages.ERROR, 'Error: That URL or title already exists.')
            return redirect(index)
        for tag_new in tags.split(" "):
            try:
                t1 = Tag.objects.get(name=tag_new)
            except Tag.DoesNotExist:
                t1 = Tag(name=tag_new)
                t1.save()
            finally:
                link.tags.add(t1)
        link.save()

    return redirect(index)
Exemplo n.º 3
0
def add_link(request):
    context = RequestContext(request)
    if request.method == 'POST':
        url = request.POST.get("url", "")

        input_tags = request.POST.get("tags", "")
        input_tags = input_tags.split(' ')

        title = request.POST.get("title", "")
        new_link = Link(title=title, url=url)

        try:
            new_link.save()
        except IntegrityError as e:
            messages.error(request, e.message)
            return redirect(index)

        for tag in input_tags:
            try:
                found = Tag.objects.get(name=tag)
                new_link.tags.add(found)
            except:
                new_tag = Tag(name=tag)
                new_tag.save()
                new_link.tags.add(new_tag)

        try:
            new_link.save()
        except Error as e:
            messages.error(request, e.message)
            return redirect(index)

    return redirect(index)
Exemplo n.º 4
0
 def save(self, commit=True):
     post = super().save(commit=False)
     if not post.hash_id:
         post.set_password(self.cleaned_data['password'])
         post.set_author(self.cleaned_data['password'])
     for tag in post.tags:
         Tag.register(tag)
     if commit:
         post.save()
     return post
Exemplo n.º 5
0
def add_link(request):
    context = RequestContext(request)
    if request.method == 'POST':
        url = request.POST.get("url", "")
        tags = request.POST.get("tags", "")
        title = request.POST.get("title", "")
        tag = Tag(name=tags)
        tag.save()
        link = Link(title=title, url=url)
        link.save()
        link.tags.add(tag)
    return redirect(index)
Exemplo n.º 6
0
def add_link(request):
    context = RequestContext(request)
    if (request.method == 'POST'):
        url = request.POST.get("url", "")
        tags = request.POST.get("tags", "")
        title = request.POST.get("title", "")
        # Create and save tag
        tag = Tag(name=tags)
        tag.save()
        # create and save link
        link = Link(title=title, url=url)
        link.save()
        # add tag to link
        link.tags.add(tag)
    return redirect(index)
Exemplo n.º 7
0
def import_tags_from_file(filepath=DEFAULT_PATH):
    for line in open(filepath):
        parts = line.split(maxsplit=1)
        if len(parts) >= 1:
            name = parts[0]
            desc = ""
            if len(parts) == 2:
                desc = parts[1].strip()
            if not re.search(tag_pattern, name):
                raise InvalidTagName(name)
            try:
                tag = Tag.objects.get(name=name)
            except Tag.DoesNotExist:
                tag = Tag(name=name)
            tag.description = desc
            tag.save()
Exemplo n.º 8
0
    def form_valid(self, form):
        blocks = {
            'ru': WordBlock.objects.create(),
            'en': WordBlock.objects.create(),
            'de': WordBlock.objects.create(),
        }

        for lang, block in blocks.items():
            for i in range(1, 4):
                value = form.cleaned_data.get('%s_value%s' % (lang, i))
                info = form.cleaned_data.get('%s_info%s' % (lang, i))
                if value:
                    Word.objects.create(
                        value=value,
                        info=info,
                        order=i,
                        lang=lang,
                        block=block,
                    )

        tag_name = form.cleaned_data.get('tag')
        tag, created = Tag.objects.get_or_create(name=tag_name)
        if created:
            tag.color = Tag.get_random_color()
            tag.save()

        Chain.objects.create(
            ru_block=blocks['ru'],
            en_block=blocks['en'],
            de_block=blocks['de'],
            part_speech=form.cleaned_data.get('part_speech'),
            tag=tag,
        )

        return super(AddView, self).form_valid(form)
Exemplo n.º 9
0
def import_tags_from_file(filepath=DEFAULT_PATH):
    for line in open(filepath):
        parts = line.split(maxsplit=1)
        if len(parts) >= 1:
            name = parts[0]
            desc = ""
            if len(parts) == 2:
                desc = parts[1].strip()
            if not re.search(tag_pattern, name):
                raise InvalidTagName(name)
            try:
                tag = Tag.objects.get(name=name)
            except Tag.DoesNotExist:
                tag = Tag(name=name)
            tag.description = desc
            tag.save()
Exemplo n.º 10
0
 def __init__(self, query):
     super().__init__(query)
     _, self._query = self._query.split('tag:')
     if self._query:
         try:
             self._tag = Tag.objects.get(name=self._query)
         except Tag.DoesNotExist:
             self._tag = Tag(name=self._query)
Exemplo n.º 11
0
    def form_valid(self, form):
        question_instance = form.save(commit=False)

        question_instance.create_date = datetime.utcnow()
        question_instance.user = self.request.user
        question_instance.save()

        tags = form.data['tags'].split(',')
        for tag_name in tags:
            tag = Tag.objects.filter(name=tag_name).first()
            if not tag:
                tag = Tag()
                tag.name = tag_name
                tag.save()
            question_instance.tags.add(tag)

        if tags:
            question_instance.save()

        return redirect('question_detail', pk=question_instance.id)
Exemplo n.º 12
0
def upload2(request):
    """Get uploaded file from form."""
    uploaded = request.read
    fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
    fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
    fileContent = uploaded(fileSize)

    """Write image to disk."""
    fn, ext = os.path.splitext(fileName)
    name = (
        fn
        + timezone.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
        + base64.urlsafe_b64encode(os.urandom(settings.SALT_LENGHT))
        + ext
    )
    fileHandler = open(settings.MEDIA_ROOT + "images/" + name, "wb")
    fileHandler.write(fileContent)
    fileHandler.close()

    """Create md5hash digest for image."""
    base64string = base64.b64encode(fileContent)
    mdfive = md5.new(base64string).hexdigest()

    """Write image data to db."""
    latitude = request.GET.get("lat")
    longitude = request.GET.get("lon")
    tags = request.GET.get("tags").split(" ")

    image = Image(title=name, md5hash=mdfive, pub_date=timezone.now(), lat=latitude, lon=longitude)
    image.save()

    for tagtext in tags:
        if Tag.objects.filter(name=tagtext).exists():
            t = Tag.objects.get(name=tagtext)
        else:
            t = Tag(name=tagtext)
            t.save()
        image.tags.add(t)
        image.save()

    return HttpResponse('{"success": true}')
Exemplo n.º 13
0
def add_link(request) :
	context = RequestContext(request)
	if request.method == 'POST':
		url = request.POST.get("url", "")
		tags = request.POST.get("tags", "").split(' ')
		title = request.POST.get("title", "")
		# TODO: Your code here!

		newLink = Link(title=title, url=url)
		newLink.save()
		for tag in tags:
			try:
				the_tag = Tag.objects.get(name=tag)
			except ObjectDoesNotExist:
				the_tag = Tag(name=tag)
				the_tag.save()

			newLink.tags.add(the_tag)
			newLink.save()

	return redirect(index)
Exemplo n.º 14
0
def update_tag_table():
    if Tag.objects.all():
        Tag.objects.all().delete()
    with open('main/data/tags.csv') as f:
        reader = csv.reader(f)
        next(reader)
        tag_objects = [
            Tag(
                user_id=row[0],
                movie_id=row[1],
                tag=row[2] if row[2] else None,
                timestamp=row[3] if row[3] else None
            )
            for row in reader
        ]
        Tag.objects.bulk_create(tag_objects)
Exemplo n.º 15
0
    def create_chain(value, order, part_speech, tag_name):
        ru_word_block = WordBlock.objects.create()
        Word.objects.create(value=value, order=order, block=ru_word_block)

        en_word_block = WordBlock.objects.create()
        Word.objects.create(value=value, order=order, block=en_word_block)

        de_word_block = WordBlock.objects.create()
        Word.objects.create(value=value, order=order, block=de_word_block)

        part_speech = part_speech

        tag = Tag.objects.create(name=tag_name)
        tag.color = Tag.get_random_color()

        return Chain.objects.create(ru_block=ru_word_block,
                                    en_block=en_word_block,
                                    de_block=de_word_block,
                                    part_speech=part_speech,
                                    tag=tag)
Exemplo n.º 16
0
 def form_valid(self, form):
     form = PartialNewPostForm(self.request.POST)
     post = form.save(commit=False)
     post.author = self.request.user
     post.slug = unidecode(post.title)
     post.slug = slugify(post.slug)
     post.save()
     if 'tags_field' in self.request.POST.keys():
         tags = self.request.POST['tags_field'].replace(', ',
                                                        ',').split(',')
         for tag_name in tags:
             tag = Tag()
             tag.post = post
             tag.name = tag_name
             tag.save()
     self.success_url = "/post/" + post.slug
     return super(NewPostView, self).form_valid(form)
Exemplo n.º 17
0
def initialLoad():
    data = [
        u'Airsoft',
        u'Apnea',
        u'Barranquismo',
        u'Beach Run',
        u'BMX',
        u'Bungee',
        u'Bodyboard',
        u'Carreras de Aventura',
        u'Carving',
        u'Cross Country',
        u'Descenso de ríos o hydrospeed',
        u'Escalada',
        u'Esquí extremo',
        u'Freeride',
        u'Freestyle',
        u'Paracaidismo',
        u'Kitesurfing',
        u'Longboard',
        u'Motocross',
        u'Paintball',
        u'Paracaidismo',
        u'Parapente',
        u'Parkour',
        u'Patinaje agresivo',
        u'Puénting',
        u'Salto base',
        u'Salto con pértiga',
        u'Surf',
        u'Sandboard',
        u'Scootering',
        u'Skateboarding',
        u'Skimming',
        u'Slackline',
        u'Snowboard',
        u'Supercross',
        u'Surf'
    ]
    for value in data:
        tag = Tag()
        tag.name = normalize(value)
        tag.display_name = value
        tag.eng_name = value
        tag.save()
Exemplo n.º 18
0
    def form_valid(self, form):
        self.object = self.get_object()  # chain

        self.object.ru_block.words.all().delete()
        self.object.en_block.words.all().delete()
        self.object.de_block.words.all().delete()

        blocks = {
            'ru': self.object.ru_block,
            'en': self.object.en_block,
            'de': self.object.de_block,
        }

        for lang, block in blocks.items():
            for i in range(1, 4):
                value = form.cleaned_data.get('%s_value%s' % (lang, i))
                info = form.cleaned_data.get('%s_info%s' % (lang, i))
                if value:
                    Word.objects.create(
                        value=value,
                        info=info,
                        order=i,
                        lang=lang,
                        block=block,
                    )

        tag_name = form.cleaned_data.get('tag')
        tag, created = Tag.objects.get_or_create(name=tag_name)
        if created:
            tag.color = Tag.get_random_color()
            tag.save()

        self.object.tag = tag
        self.object.part_speech = form.cleaned_data.get('part_speech')
        self.object.save()

        return HttpResponseRedirect(self.get_success_url())
Exemplo n.º 19
0
def add_page(request):
    """Page with a form for creating an article."""
    if no_access(request, 'pages'):
        return HttpResponseRedirect(reverse('no_access'))
    grp = get_info(request)
    error = ''
    p = {'url':'', 'title':'', 'text':'', 'pic':'', 'date':'', 'paragraphs':[], 'access':'', 'status':'', 'order':'', 'tags':''}
    if request.method == 'POST':
        try:
            url = request.POST['url']
            title = request.POST['title']
            pic = request.POST['pic']
            order = int(request.POST['order'])
            access = request.POST['access']
            status = request.POST['status']
            text = request.POST['text']
            tags = request.POST['tags']
            p['url'] = url
            p['title'] = title
            p['text'] = text
            p['pic'] = pic
            p['access'] = access
            p['status'] = status
            p['order'] = order
            p['tags'] = tags
            parags = []
            taglist = [x.strip() for x in tags.split(',')]
            i = 1
            while 'section_title_'+str(i) in request.POST:
                parags.append({'title':request.POST['section_title_'+str(i)], 'text':request.POST['section_text_'+str(i)], 'order':i})
                i += 1
            p['paragraphs'] = parags
            if title == '':
                raise Exception('Enter page title.')
            if url == '':
                raise Exception('Enter page URL')
            if order < 0:
                raise Exception('Order must be a positive number.')
            if len(Page.objects.filter(order=order)) > 0:
                raise Exception('Order number must be unique')
            for par in parags:
                if par['title'] == '':
                    raise Exception('Sections must have titles')
        except Exception as ex:
            error = ex
        else:
            pag = Page(title=title, url=url, pic=pic, order=order, access=access, status=status, text=text, add_date=datetime.now().date(), added_by=request.user.username)
            pag.save()
            for tag in taglist:
                if len(Tag.objects.filter(name=tag)) == 1:
                    pag.tags.add(Tag.objects.get(name=tag))
                else:
                    tg = Tag(name=tag)
                    tg.save()
                    pag.tags.add(tg)
            pag.save()
            for parag in parags:
                paragraph = Paragraph(title=parag['title'], text=parag['text'], order=parag['order'], page=pag)
                paragraph.save()
            
            return HttpResponseRedirect(reverse('admin_pages'))
    template = loader.get_template('main/admin_edit_page.html')
    context = RequestContext(request, {
        'page':p,
        'error_message':error,
        'edit':'no',
        'group':grp
    })
    return HttpResponse(template.render(context))
Exemplo n.º 20
0
def create_tags(n):
    for _ in range(n):
        t = Tag(title=fake.word())
        t.save()
Exemplo n.º 21
0
def add_page(request):
    """Page with a form for creating an article."""
    if no_access(request, 'pages'):
        return HttpResponseRedirect(reverse('no_access'))
    grp = get_info(request)
    error = ''
    p = {
        'url': '',
        'title': '',
        'text': '',
        'pic': '',
        'date': '',
        'paragraphs': [],
        'access': '',
        'status': '',
        'order': '',
        'tags': ''
    }
    if request.method == 'POST':
        try:
            url = request.POST['url']
            title = request.POST['title']
            pic = request.POST['pic']
            order = int(request.POST['order'])
            access = request.POST['access']
            status = request.POST['status']
            text = request.POST['text']
            tags = request.POST['tags']
            p['url'] = url
            p['title'] = title
            p['text'] = text
            p['pic'] = pic
            p['access'] = access
            p['status'] = status
            p['order'] = order
            p['tags'] = tags
            parags = []
            taglist = [x.strip() for x in tags.split(',')]
            i = 1
            while 'section_title_' + str(i) in request.POST:
                parags.append({
                    'title': request.POST['section_title_' + str(i)],
                    'text': request.POST['section_text_' + str(i)],
                    'order': i
                })
                i += 1
            p['paragraphs'] = parags
            if title == '':
                raise Exception('Enter page title.')
            if url == '':
                raise Exception('Enter page URL')
            if order < 0:
                raise Exception('Order must be a positive number.')
            if len(Page.objects.filter(order=order)) > 0:
                raise Exception('Order number must be unique')
            for par in parags:
                if par['title'] == '':
                    raise Exception('Sections must have titles')
        except Exception as ex:
            error = ex
        else:
            pag = Page(title=title,
                       url=url,
                       pic=pic,
                       order=order,
                       access=access,
                       status=status,
                       text=text,
                       add_date=datetime.now().date(),
                       added_by=request.user.username)
            pag.save()
            for tag in taglist:
                if len(Tag.objects.filter(name=tag)) == 1:
                    pag.tags.add(Tag.objects.get(name=tag))
                else:
                    tg = Tag(name=tag)
                    tg.save()
                    pag.tags.add(tg)
            pag.save()
            for parag in parags:
                paragraph = Paragraph(title=parag['title'],
                                      text=parag['text'],
                                      order=parag['order'],
                                      page=pag)
                paragraph.save()

            return HttpResponseRedirect(reverse('admin_pages'))
    template = loader.get_template('main/admin_edit_page.html')
    context = RequestContext(request, {
        'page': p,
        'error_message': error,
        'edit': 'no',
        'group': grp
    })
    return HttpResponse(template.render(context))
Exemplo n.º 22
0
def pages_edit(request, page_order):
    """Page with a form for editing article."""
    if no_access(request, 'pages'):
        return HttpResponseRedirect(reverse('no_access'))
    grp = get_info(request)
    error = ''
    if request.method == 'POST':
        try:
            url = request.POST['url']
            title = request.POST['title']
            pic = request.POST['pic']
            order = int(request.POST['order'])
            order_old = int(request.POST['order_old'])
            access = request.POST['access']
            status = request.POST['status']
            text = request.POST['text']
            tags = request.POST['tags']
            taglist = [x.strip() for x in tags.split(',')]
            parags = []
            i = 1
            while 'section_title_' + str(i) in request.POST:
                parags.append({
                    'title': request.POST['section_title_' + str(i)],
                    'text': request.POST['section_text_' + str(i)],
                    'order': i
                })
                i += 1
            if title == '':
                raise Exception('Enter page title.')
            if order < 0:
                raise Exception('Order must be a positive number.')
            if len(Page.objects.filter(
                    order=order)) > 0 and order != order_old:
                raise Exception('Order number must be unique')
            for par in parags:
                if par['title'] == '':
                    raise Exception('Sections must have titles')
        except Exception as ex:
            error = ex
        else:
            pag = Page.objects.get(url=url)
            pag.title = title
            pag.pic = pic
            pag.order = order
            pag.access = access
            pag.status = status
            pag.text = text
            Paragraph.objects.filter(page=pag).delete()
            pag.tags.clear()
            for tag in taglist:
                if len(Tag.objects.filter(name=tag)) == 1:
                    pag.tags.add(Tag.objects.get(name=tag))
                else:
                    tg = Tag(name=tag)
                    tg.save()
                    pag.tags.add(tg)
            pag.save()
            for parag in parags:
                paragraph = Paragraph(title=parag['title'],
                                      text=parag['text'],
                                      order=parag['order'],
                                      page=pag)
                paragraph.save()
            return HttpResponseRedirect(reverse('admin_pages'))
    if len(Page.objects.filter(order=page_order)) == 0:
        return HttpResponseRedirect(reverse('admin_pages'))
    page = Page.objects.get(order=page_order)
    strtgs = ''
    tgs = page.tags.all()
    for tag in tgs:
        strtgs += tag.name + ', '
    if strtgs != '':
        strtgs = strtgs[:-2]
    p = {
        'url': page.url,
        'title': page.title,
        'text': page.text,
        'pic': page.pic,
        'date': page.add_date,
        'paragraphs': [],
        'access': page.access,
        'status': page.status,
        'order': page.order,
        'tags': strtgs
    }
    pars = Paragraph.objects.filter(page=page).order_by('order')
    for par in pars:
        p['paragraphs'].append({
            'title': par.title,
            'text': par.text,
            'order': par.order
        })
    template = loader.get_template('main/admin_edit_page.html')
    context = RequestContext(request, {
        'page': p,
        'error_message': error,
        'edit': 'yes',
        'group': grp
    })
    return HttpResponse(template.render(context))
Exemplo n.º 23
0
    def handle(self, n, **options):
        # Create 5 tags
        Tag.objects.bulk_create([
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=True),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=True),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=True),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=True),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=True),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=False),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=False),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=False),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=False),
            Tag(tag_he=silly.title(), tag_en=silly.title(), featured=False),
        ])

        for i in range(n):
            # Create random mosaic site
            s = MosaicSite()
            s.site_id = silly.title()
            s.title_he = silly.name()
            s.title_en = silly.name()
            s.origin_he = silly.title()
            s.origin_en = silly.title()
            s.story_he = silly.thing()
            s.story_en = silly.thing()
            s.archeological_context = random.choice(['church', 'synagogue', 'public'])
            s.period = 'byzantine'
            s.video_id = silly.title()
            s.comments = silly.thing()
            s.featured = random.choice([True, False])
            s.latitude = silly.number()
            s.longitude = silly.number()
            s.save()
            for j in range(3):
                mi = MosaicItem()
                mi.mosaic_site = s
                mi.misp_rashut = silly.title()
                mi.length = silly.number()
                mi.width = silly.number()
                mi.area = silly.number()
                mi.rishayon = silly.title()
                mi.materials = [random.choice(Materials.CHOICES)[0]]
                mi.year = silly.datetime().year
                mi.displayed_at = silly.address()
                mi.description_he = silly.thing()
                mi.description_en = silly.thing()
                mi.bibliography_he = silly.thing()
                mi.bibliography_en = silly.thing()
                mi.save()
                mi.tags.add(Tag.objects.all().order_by('?')[0])
                for k in range(3):
                    mp = MosaicPicture()
                    mp.mosaic = mi
                    mp.is_cover = random.choice([True, False])
                    mp.order_priority = random.randint(1, 100)
                    filename = os.path.join(
                        settings.BASE_DIR, 'mosaic_images/{}.jpg'.format(random.randint(1, 12))
                    )
                    mp.picture = UploadedFile(open(filename, "br"))
                    mp.negative_id = silly.number()
                    mp.photographer_name_he = silly.name()
                    mp.photographer_name_en = silly.name()
                    mp.taken_at = silly.country()
                    mp.picture_type = random.choice(PictureType.CHOICES)[0]
                    mp.taken_date = silly.datetime().date()
                    mp.comments_he = silly.thing()
                    mp.comments_en = silly.thing()
                    mp.full_clean()
                    mp.save()
                    mp.tags.add(Tag.objects.all().order_by('?')[0])
Exemplo n.º 24
0
    def handle(self, *args, **options):
        # Создание пользователей
        for i in range(1, 10000):
            user = User.objects.create_user("username_" + str(i),
                                            password="******",
                                            email="email_" + str(i))
            user.profile.nick_name = "nick_name_" + str(i)
            user.save()
        users = User.objects.all()

        # Создание тегов
        for i in range(1, 1000):
            try:
                Tag(name="тег_" + str(i)).save()
            except Exception:
                pass
        tags = Tag.objects.all()

        # Создание вопросов
        for i in range(1, 10000):
            q = Question(
                title="Заголовок вопроса " + str(i),
                text=("Текст вопроса " + str(i) + " ") * random.randint(1, 50),
                user=random.choice(users),
            )
            q.save()
            for _ in range(0, random.randint(0, 3)):
                q.tags.add(random.choice(tags))
        questions = Question.objects.all()

        # Создание ответов
        for i in range(1, 10000):
            Answer(text=("Текст ответа " + str(i) + " ") *
                   random.randint(1, 50),
                   is_correct=bool(random.randint(0, 1)),
                   question=random.choice(questions),
                   user=random.choice(users)).save()
        answers = Answer.objects.all()

        # Создание лайков вопросов
        for _ in range(1, 10000):
            like = QuestionLike(question=random.choice(questions),
                                user=random.choice(users),
                                is_like=bool(random.randint(0, 1)))
            like.save()
            if like.is_like:
                like.question.rating += 1
            else:
                like.question.rating -= 1
            like.question.save()

        # Создание лайков ответов
        for _ in range(0, 100001):
            like = AnswerLike(answer=random.choice(answers),
                              user=random.choice(users),
                              is_like=bool(random.randint(0, 1)))
            like.save()
            if like.is_like:
                like.answer.rating += 1
            else:
                like.answer.rating -= 1
            like.answer.save()


# python manage.py database_data
Exemplo n.º 25
0
def pages_edit(request, page_order):
    """Page with a form for editing article."""
    if no_access(request, 'pages'):
        return HttpResponseRedirect(reverse('no_access'))
    grp = get_info(request)
    error = ''
    if request.method == 'POST':
        try:
            url = request.POST['url']
            title = request.POST['title']
            pic = request.POST['pic']
            order = int(request.POST['order'])
            order_old = int(request.POST['order_old'])
            access = request.POST['access']
            status = request.POST['status']
            text = request.POST['text']
            tags = request.POST['tags']
            taglist = [x.strip() for x in tags.split(',')]
            parags = []
            i = 1
            while 'section_title_'+str(i) in request.POST:
                parags.append({'title':request.POST['section_title_'+str(i)], 'text':request.POST['section_text_'+str(i)], 'order':i})
                i += 1
            if title == '':
                raise Exception('Enter page title.')
            if order < 0:
                raise Exception('Order must be a positive number.')
            if len(Page.objects.filter(order=order)) > 0 and order != order_old:
                raise Exception('Order number must be unique')
            for par in parags:
                if par['title'] == '':
                    raise Exception('Sections must have titles')
        except Exception as ex:
            error = ex
        else:
            pag = Page.objects.get(url=url)
            pag.title = title
            pag.pic = pic
            pag.order = order
            pag.access = access
            pag.status = status
            pag.text = text
            Paragraph.objects.filter(page=pag).delete()
            pag.tags.clear()
            for tag in taglist:
                if len(Tag.objects.filter(name=tag)) == 1:
                    pag.tags.add(Tag.objects.get(name=tag))
                else:
                    tg = Tag(name=tag)
                    tg.save()
                    pag.tags.add(tg)
            pag.save()
            for parag in parags:
                paragraph = Paragraph(title=parag['title'], text=parag['text'], order=parag['order'], page=pag)
                paragraph.save()
            return HttpResponseRedirect(reverse('admin_pages'))
    if len(Page.objects.filter(order=page_order)) == 0:
        return HttpResponseRedirect(reverse('admin_pages'))
    page = Page.objects.get(order=page_order)
    strtgs = ''
    tgs = page.tags.all()
    for tag in tgs:
        strtgs += tag.name + ', '
    if strtgs != '':
        strtgs = strtgs[:-2]
    p = {'url':page.url, 'title':page.title, 'text':page.text, 'pic':page.pic, 'date':page.add_date, 'paragraphs':[], 'access':page.access, 'status':page.status, 'order':page.order, 'tags':strtgs}
    pars = Paragraph.objects.filter(page=page).order_by('order')
    for par in pars:
        p['paragraphs'].append({'title':par.title, 'text':par.text, 'order':par.order})
    template = loader.get_template('main/admin_edit_page.html')
    context = RequestContext(request, {
        'page':p,
        'error_message':error,
        'edit':'yes',
        'group':grp
    })
    return HttpResponse(template.render(context))