django.http.HttpResponseRedirect

Here are the examples of the python api django.http.HttpResponseRedirect taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: jaikuenginepatch
Source File: views.py
View license
@alternate_nick
def actor_overview(request, nick, format='html'):
  nick = clean.nick(nick)

  view = api.actor_lookup_nick(request.user, nick)

  if not view:
    raise exception.UserDoesNotExistError(nick, request.user)

  if not request.user or view.nick != request.user.nick:
    # Instead of displaying the overview, redirect to the public-facing page
    return http.HttpResponseRedirect(view.url())

  handled = common_views.handle_view_action(
      request,
      { 
        'entry_remove': request.path,
        'entry_remove_comment': request.path,
        'entry_mark_as_spam': request.path,
        'presence_set': request.path,
        'settings_hide_comments': request.path,
        'post': request.path,
      }
  )
  if handled:
    return handled

  per_page = ENTRIES_PER_PAGE
  offset, prev = util.page_offset(request)

  inbox = api.inbox_get_actor_overview(request.user,  
                                       view.nick,
                                       limit=(per_page + 1), 
                                       offset=offset)

  actor_streams = api.stream_get_actor(request.user, view.nick)
  entries, more = _get_inbox_entries(request, inbox,
                                     view.extra.get('comments_hide', 0))
  contacts, channels, streams, entries = _assemble_inbox_data(request,
                                                              entries,
                                                              actor_streams,
                                                              view)

  # Check for unconfirmed emails
  unconfirmeds = api.activation_get_actor_email(request.user, view.nick)
  if unconfirmeds:
    unconfirmed_email = unconfirmeds[0].content

  # If not logged in, cannot write
  is_owner = False
  try:
    is_owner = view.nick == request.user.nick
  except:
    pass
  presence = api.presence_get(request.user, view.nick)

  # for sidebar streams
  view_streams = _get_sidebar_streams(actor_streams, streams)

  # for sidebar_contacts
  contacts_count = view.extra.get('contact_count', 0)
  contacts_more = contacts_count > CONTACTS_PER_PAGE

  # for sidebar channels
  channels_count = view.extra.get('channel_count', 0)
  channels_more = channels_count > CHANNELS_PER_PAGE

  # Config for the template
  green_top = True
  sidebar_green_top = True
  selectable_icons = display.SELECTABLE_ICONS

  area = 'home'

  # TODO(tyler/termie):  This conflicts with the global settings import.
  # Also, this seems fishy.  Do none of the settings.* items work in templates?
  import settings
  
  c = template.RequestContext(request, locals())

  if format == 'html':
    t = loader.get_template('overview.html')
    return http.HttpResponse(t.render(c))
  elif format == 'json':
    t = loader.get_template('overview.json')
    r = util.HttpJsonResponse(t.render(c), request)
    return r
  elif format == 'atom':
    t = loader.get_template('overview.atom')
    r = util.HttpAtomResponse(t.render(c), request)
    return r
  elif format == 'rss':
    t = loader.get_template('overview.rss')
    r = util.HttpRssResponse(t.render(c), request)
    return r

Example 2

Project: hubplus
Source File: views.py
View license
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """
    photo = get_object_or_404(Image, id=id)
    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404
    photo_url = photo.get_display_url()
    
    tribes = []
    projects = []
    
    # Build a list of tribes and the photos from the pool
    for tribe in Tribe.objects.filter(members=request.user):
        phototribe = Tribe.objects.get(pk=tribe.id)
        if phototribe.photos.filter(photo=photo).count():
            tribes.append({
                "name": tribe.name,
                "slug": tribe.slug,
                "id": tribe.id,
                "has_photo": True,
            })
        else:
            tribes.append({
                "name": tribe.name,
                "slug": tribe.slug,
                "id": tribe.id,
                "has_photo": False,
            })

    # Build a list of projects and the photos from the pool
    for project in Project.objects.filter(members__user=request.user):
        photoproject = Project.objects.get(pk=project.id)
        if photoproject.photos.filter(photo=photo).count():
            projects.append({
                "name": project.name,
                "slug": project.slug,
                "id": project.id,
                "has_photo": True,
            })
        else:
            projects.append({
                "name": project.name,
                "slug": project.slug,
                "id": project.id,
                "has_photo": False,
            })

    title = photo.title
    host = "http://%s" % get_host(request)
    if photo.member == request.user:
        is_me = True
    else:
        is_me = False
    # TODO: check for authorized user and catch errors
    if is_me:
        if request.method == "POST" and request.POST["action"] == "add_to_project":
            projectid = request.POST["project"]
            myproject = Project.objects.get(pk=projectid)
            if not myproject.photos.filter(photo=photo).count():
                myproject.photos.create(photo=photo)
                request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
            else:
                # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

            return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))
        
        if request.method == "POST":
            if request.POST["action"] == "addtotribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if not mytribe.photos.filter(photo=photo).count():
                    mytribe.photos.create(photo=photo)
                    request.user.message_set.create(message=_("Successfully add photo '%s' to tribe") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to tribe because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "removefromtribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if mytribe.photos.filter(photo=photo).count():
                    mytribe.photos.filter(photo=photo).delete()
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from tribe") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from tribe.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "addtoproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if not myproject.photos.filter(photo=photo).count():
                    myproject.photos.create(photo=photo)
                    request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "removefromproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if myproject.photos.filter(photo=photo).count():
                    myproject.photos.filter(photo=photo).delete()
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from project") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from project.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

    return render_to_response(template_name, {
        "host": host, 
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
        "projects": projects,
        "tribes": tribes,
    }, context_instance=RequestContext(request))

Example 3

Project: seantis-questionnaire
Source File: views.py
View license
@commit_on_success
def questionnaire(request, runcode=None, qs=None):
    """
    Process submitted answers (if present) and redirect to next page

    If this is a POST request, parse the submitted data in order to store
    all the submitted answers.  Then return to the next questionset or
    return a completed response.

    If this isn't a POST request, redirect to the main page.

    We only commit on success, to maintain consistency.  We also specifically
    rollback if there were errors processing the answers for this questionset.
    """
    if use_session:
        session_runcode = request.session.get('runcode', None)
        if session_runcode is not None:
            runcode = session_runcode

        session_qs = request.session.get('qs', None)
        if session_qs is not None:
            qs = session_qs

    # if runcode provided as query string, redirect to the proper page
    if not runcode:
        runcode = request.GET.get('runcode')
        if not runcode:
            return HttpResponseRedirect("/")
        else:
            if not use_session:
                args = [runcode, ]
            else:
                request.session['runcode'] = runcode
                args = []
            return HttpResponseRedirect(reverse("questionnaire", args=args))

    runinfo = get_runinfo(runcode)

    if not runinfo:
        transaction.commit()
        return HttpResponseRedirect('/')

    # let the runinfo have a piggy back ride on the request
    # so we can easily use the runinfo in places like the question processor
    # without passing it around
    request.runinfo = runinfo

    if not qs:
        # Only change the language to the subjects choice for the initial
        # questionnaire page (may be a direct link from an email)
        if hasattr(request, 'session'):
            request.session['django_language'] = runinfo.subject.language
            translation.activate(runinfo.subject.language)

    if 'lang' in request.GET:
        return set_language(request, runinfo, request.path)

    # --------------------------------
    # --- Handle non-POST requests ---
    # --------------------------------

    if request.method != "POST":
        if qs is not None:
            qs = get_object_or_404(QuestionSet, sortid=qs, questionnaire=runinfo.questionset.questionnaire)
            if runinfo.random.startswith('test:'):
                pass # ok for testing
            elif qs.sortid > runinfo.questionset.sortid:
                # you may jump back, but not forwards
                return redirect_to_qs(runinfo, request)
            runinfo.questionset = qs
            runinfo.save()
            transaction.commit()
        # no questionset id in URL, so redirect to the correct URL
        if qs is None:
            return redirect_to_qs(runinfo, request)
        questionset_start.send(sender=None, runinfo=runinfo, questionset=qs)
        return show_questionnaire(request, runinfo)

    # -------------------------------------
    # --- Process POST with QuestionSet ---
    # -------------------------------------

    # if the submitted page is different to what runinfo says, update runinfo
    # XXX - do we really want this?
    qs = request.POST.get('questionset_id', qs)
    try:
        qsobj = QuestionSet.objects.filter(pk=qs)[0]
        if qsobj.questionnaire == runinfo.questionset.questionnaire:
            if runinfo.questionset != qsobj:
                runinfo.questionset = qsobj
                runinfo.save()
    except:
        pass

    questionnaire = runinfo.questionset.questionnaire
    questionset = runinfo.questionset

    # to confirm that we have the correct answers
    expected = questionset.questions()

    items = request.POST.items()
    extra = {} # question_object => { "ANSWER" : "123", ... }

    # this will ensure that each question will be processed, even if we did not receive
    # any fields for it. Also works to ensure the user doesn't add extra fields in
    for x in expected:
        items.append( (u'question_%s_Trigger953' % x.number, None) )

    # generate the answer_dict for each question, and place in extra
    for item in items:
        key, value = item[0], item[1]
        if key.startswith('question_'):
            answer = key.split("_", 2)
            question = get_question(answer[1], questionnaire)
            if not question:
                logging.warn("Unknown question when processing: %s" % answer[1])
                continue
            extra[question] = ans = extra.get(question, {})
            if(len(answer) == 2):
                ans['ANSWER'] = value
            elif(len(answer) == 3):
                ans[answer[2]] = value
            else:
                logging.warn("Poorly formed form element name: %r" % answer)
                continue
            extra[question] = ans

    errors = {}
    for question, ans in extra.items():
        if not question_satisfies_checks(question, runinfo):
            continue
        if u"Trigger953" not in ans:
            logging.warn("User attempted to insert extra question (or it's a bug)")
            continue
        try:
            cd = question.getcheckdict()
            # requiredif is the new way
            depon = cd.get('requiredif',None) or cd.get('dependent',None)
            if depon:
                depparser = BooleanParser(dep_check, runinfo, extra)
                if not depparser.parse(depon):
                    # if check is not the same as answer, then we don't care
                    # about this question plus we should delete it from the DB
                    delete_answer(question, runinfo.subject, runinfo.runid)
                    if cd.get('store', False):
                        runinfo.set_cookie(question.number, None)
                    continue
            add_answer(runinfo, question, ans)
            if cd.get('store', False):
                runinfo.set_cookie(question.number, ans['ANSWER'])
        except AnswerException, e:
            errors[question.number] = e
        except Exception:
            logging.exception("Unexpected Exception")
            transaction.rollback()
            raise

    if len(errors) > 0:
        res = show_questionnaire(request, runinfo, errors=errors)
        transaction.rollback()
        return res

    questionset_done.send(sender=None,runinfo=runinfo,questionset=questionset)

    next = questionset.next()
    while next and not questionset_satisfies_checks(next, runinfo):
        next = next.next()
    runinfo.questionset = next
    runinfo.save()
    if use_session:
        request.session['prev_runcode'] = runinfo.random

    if next is None: # we are finished
        return finish_questionnaire(request, runinfo, questionnaire)

    transaction.commit()
    return redirect_to_qs(runinfo, request)

Example 4

Project: django-forms-builder
Source File: admin.py
View license
    def entries_view(self, request, form_id, show=False, export=False,
                     export_xls=False):
        """
        Displays the form entries in a HTML table with option to
        export as CSV file.
        """
        if request.POST.get("back"):
            bits = (self.model._meta.app_label, self.model.__name__.lower())
            change_url = reverse("admin:%s_%s_change" % bits, args=(form_id,))
            return HttpResponseRedirect(change_url)
        form = get_object_or_404(self.model, id=form_id)
        post = request.POST or None
        args = form, request, self.formentry_model, self.fieldentry_model, post
        entries_form = EntriesForm(*args)
        delete = "%s.delete_formentry" % self.formentry_model._meta.app_label
        can_delete_entries = request.user.has_perm(delete)
        submitted = entries_form.is_valid() or show or export or export_xls
        export = export or request.POST.get("export")
        export_xls = export_xls or request.POST.get("export_xls")
        if submitted:
            if export:
                response = HttpResponse(content_type="text/csv")
                fname = "%s-%s.csv" % (form.slug, slugify(now().ctime()))
                attachment = "attachment; filename=%s" % fname
                response["Content-Disposition"] = attachment
                queue = StringIO()
                try:
                    csv = writer(queue, delimiter=CSV_DELIMITER)
                    writerow = csv.writerow
                except TypeError:
                    queue = BytesIO()
                    delimiter = bytes(CSV_DELIMITER, encoding="utf-8")
                    csv = writer(queue, delimiter=delimiter)
                    writerow = lambda row: csv.writerow([c.encode("utf-8")
                        if hasattr(c, "encode") else c for c in row])
                writerow(entries_form.columns())
                for row in entries_form.rows(csv=True):
                    writerow(row)
                data = queue.getvalue()
                response.write(data)
                return response
            elif XLWT_INSTALLED and export_xls:
                response = HttpResponse(content_type="application/vnd.ms-excel")
                fname = "%s-%s.xls" % (form.slug, slugify(now().ctime()))
                attachment = "attachment; filename=%s" % fname
                response["Content-Disposition"] = attachment
                queue = BytesIO()
                workbook = xlwt.Workbook(encoding='utf8')
                sheet = workbook.add_sheet(form.title[:31])
                for c, col in enumerate(entries_form.columns()):
                    sheet.write(0, c, col)
                for r, row in enumerate(entries_form.rows(csv=True)):
                    for c, item in enumerate(row):
                        if isinstance(item, datetime):
                            item = item.replace(tzinfo=None)
                            sheet.write(r + 2, c, item, XLWT_DATETIME_STYLE)
                        else:
                            sheet.write(r + 2, c, item)
                workbook.save(queue)
                data = queue.getvalue()
                response.write(data)
                return response
            elif request.POST.get("delete") and can_delete_entries:
                selected = request.POST.getlist("selected")
                if selected:
                    try:
                        from django.contrib.messages import info
                    except ImportError:
                        def info(request, message, fail_silently=True):
                            request.user.message_set.create(message=message)
                    entries = self.formentry_model.objects.filter(id__in=selected)
                    count = entries.count()
                    if count > 0:
                        entries.delete()
                        message = ungettext("1 entry deleted",
                                            "%(count)s entries deleted", count)
                        info(request, message % {"count": count})
        template = "admin/forms/entries.html"
        context = {"title": _("View Entries"), "entries_form": entries_form,
                   "opts": self.model._meta, "original": form,
                   "can_delete_entries": can_delete_entries,
                   "submitted": submitted,
                   "xlwt_installed": XLWT_INSTALLED}
        return render(request, template, context)

Example 5

Project: coursys
Source File: views.py
View license
def _edit_pagefile(request, course_slug, page_label, kind):
    """
    View to create and edit pages
    """
    if request.method == 'POST' and 'delete' in request.POST and request.POST['delete'] == 'yes':
        return _delete_pagefile(request, course_slug, page_label, kind)
    with django.db.transaction.atomic():
        offering = get_object_or_404(CourseOffering, slug=course_slug)
        if page_label:
            page = get_object_or_404(Page, offering=offering, label=page_label)
            version = page.current_version()
            member = _check_allowed(request, offering, page.can_write, page.editdate())
            old_label = page.label
        else:
            page = None
            version = None
            member = _check_allowed(request, offering, offering.page_creators()) # users who can create pages
            old_label = None

        if isinstance(member, PagePermission):
            return ForbiddenResponse(request, 'Editing of pages by additional-permission holders is not implemented. Sorry')

        # make sure we're looking at the right "kind" (page/file)
        if not kind:
            kind = "file" if version.is_filepage() else "page"

        # get the form class we need
        if kind == "page":
            Form = EditPageForm
        else:
            Form = EditFileForm
        
        # check that we have an allowed member of the course (and can continue)
        if not member:
            return ForbiddenResponse(request, 'Not allowed to edit/create this '+kind+'.')
        restricted = False
        if member.role == 'STUD':
            # students get the restricted version of the form
            Form = Form.restricted_form
            restricted = True
        
        if request.method == 'POST':
            form = Form(instance=page, offering=offering, data=request.POST, files=request.FILES)
            if form.is_valid():
                instance = form.save(editor=member)
                
                # clean up weirdness from restricted form
                if 'label' not in form.cleaned_data:
                    # happens when student edits an existing page
                    instance.label = page.label
                if 'can_write' not in form.cleaned_data:
                    # happens only when students create a page
                    instance.can_write = 'STUD'
                
                if not restricted and 'releasedate' in form.cleaned_data:
                    instance.set_releasedate(form.cleaned_data['releasedate'])
                elif not restricted:
                    instance.set_releasedate(None)

                if not restricted and 'editdate' in form.cleaned_data:
                    instance.set_editdate(form.cleaned_data['editdate'])
                elif not restricted:
                    instance.set_editdate(None)

                instance.redirect = None

                if old_label and old_label != instance.label:
                    # page has been moved to a new URL: leave a redirect in its place
                    redir_page = Page(offering=instance.offering, label=old_label,
                                      can_read=instance.can_read, can_write=offering.page_creators())
                    redir_page.set_releasedate(instance.releasedate())
                    redir_page.set_editdate(instance.editdate())
                    redir_page.save()
                    redir_version = PageVersion(page=redir_page, title=version.title, redirect=instance.label,
                                                editor=member, comment='automatically generated on label change')
                    redir_version.set_redirect_reason('rename')
                    redir_version.save()
                    messages.info(request, 'Page label changed: the old location (%s) will redirect to this page.' % (old_label,))

                instance.save()
                
                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                      description="Edited page %s in %s." % (instance.label, offering),
                      related_object=instance)
                l.save()
                if page:
                    messages.success(request, "Edited "+kind+" \"%s\"." % (instance.label))
                else:
                    messages.success(request, "Created "+kind+" \"%s\"." % (instance.label))

                if not page and instance.label == 'Index' and not offering.url():
                    # new Index page but no existing course URL: set as course web page
                    url = settings.BASE_ABS_URL + instance.get_absolute_url()
                    offering.set_url(url)
                    offering.save()
                    messages.info(request, "Set course URL to new Index page.")
                
                return HttpResponseRedirect(reverse('pages.views.view_page', kwargs={'course_slug': course_slug, 'page_label': instance.label}))
        else:
            form = Form(instance=page, offering=offering)
            if 'label' in request.GET:
                label = request.GET['label']
                if label == 'Index':
                    form.initial['title'] = offering.name()
                    form.fields['label'].help_text += u'\u2014the label "Index" indicates the front page for this course.'
                elif label == MACRO_LABEL:
                    form.initial['can_read'] = 'INST'
                    form.initial['can_write'] = 'INST'
                    form.initial['title'] = MACRO_LABEL
                else:
                    form.initial['title'] = label.title()
                form.initial['label'] = label

        context = {
            'offering': offering,
            'page': page,
            'form': form,
            'kind': kind.title(),
            'is_macro_page': form.initial.get('title', None) == MACRO_LABEL,
        }
        return render(request, 'pages/edit_page.html', context)

Example 6

Project: snowy
Source File: admin.py
View license
    def render_revision_form(self, request, obj, version, revision, context, template, redirect_url):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        ordered_objects = opts.get_ordered_objects()
        app_label = opts.app_label
        object_version = version.object_version
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            for FormSet in self.get_formsets(request, new_object):
                formset = FormSet(request.POST, request.FILES,
                                  instance=new_object)
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    self.save_formset(request, form, formset, change=True)
                change_message = _(u"Reverted to previous version, saved on %(datetime)s") % {"datetime": format(version.revision.date_created, _(settings.DATETIME_FORMAT))}
                self.log_change(request, new_object, change_message)
                self.message_user(request, _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.') % {"model": opts.verbose_name, "name": unicode(obj)})
                return HttpResponseRedirect(redirect_url)
        else:
            initial = deserialized_model_to_dict(object_version, revision)
            form = ModelForm(instance=obj, initial=initial)
            for FormSet in self.get_formsets(request, obj):
                formset = FormSet(instance=obj)
                try:
                    attname = FormSet.fk.attname
                except AttributeError:
                    # This is a GenericInlineFormset, or similar.
                    attname = FormSet.ct_fk_field_name
                pk_name = FormSet.model._meta.pk.name
                initial_overrides = dict([(getattr(version.object, pk_name), version) for version in revision if version.object.__class__ == FormSet.model and unicode(getattr(version.object, attname)) == unicode(object_id)])
                initial = formset.initial
                for initial_row in initial:
                    pk = initial_row[pk_name]
                    if pk in initial_overrides:
                         initial_row.update(deserialized_model_to_dict(initial_overrides[pk], revision))
                         del initial_overrides[pk]
                    else:
                       initial_row["DELETE"] = True
                initial.extend([deserialized_model_to_dict(override, revision) for override in initial_overrides.values()])
                # HACK: no way to specify initial values.
                formset._total_form_count = len(initial)
                formset.initial = initial
                formset._construct_forms()
                formsets.append(formset)
        # Generate the context.
        adminForm = admin.helpers.AdminForm(form, self.get_fieldsets(request, obj), self.prepopulated_fields)
        media = self.media + adminForm.media
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            inline_admin_formset = admin.helpers.InlineAdminFormSet(inline, formset, fieldsets)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        context.update({"adminform": adminForm,
                        "object_id": obj.pk,
                        "original": obj,
                        "is_popup": False,
                        "media": mark_safe(media),
                        "inline_admin_formsets": inline_admin_formsets,
                        "errors": admin.helpers.AdminErrorList(form, formsets),
                        "root_path": self.admin_site.root_path,
                        "app_label": app_label,
                        "add": False,
                        "change": True,
                        "has_add_permission": self.has_add_permission(request),
                        "has_change_permission": self.has_change_permission(request, obj),
                        "has_delete_permission": self.has_delete_permission(request, obj),
                        "has_file_field": True, # FIXME - this should check if form or formsets have a FileField,
                        "has_absolute_url": hasattr(self.model, "get_absolute_url"),
                        "ordered_objects": ordered_objects,
                        "form_url": mark_safe(request.path),
                        "opts": opts,
                        "content_type_id": ContentType.objects.get_for_model(self.model).id,
                        "save_as": self.save_as,
                        "save_on_top": self.save_on_top,
                        "root_path": self.admin_site.root_path,})
        return render_to_response(template, context, RequestContext(request))

Example 7

Project: tendenci
Source File: views.py
View license
@is_enabled('jobs')
@login_required
def add(request, form_class=JobForm, template_name="jobs/add.html",
        object_type=Job, success_redirect='job', thankyou_redirect='job.thank_you'):

    require_payment = get_setting('module', 'jobs',
                                    'jobsrequirespayment')

    can_add_active = has_perm(request.user, 'jobs.add_job')

    content_type = get_object_or_404(
        ContentType,
        app_label=object_type._meta.app_label,
        model=object_type._meta.model_name
    )

    if request.user.profile.is_superuser:
        category_form_class = CategoryForm
    else:
        category_form_class = CategoryForm2

    form = form_class(request.POST or None, request.FILES or None, user=request.user)
    # adjust the fields depending on user type
    if not require_payment:
        del form.fields['payment_method']
        del form.fields['list_type']

    if request.method == "POST":
        if require_payment:
            is_free = is_free_listing(request.user,
                               request.POST.get('pricing', 0),
                               request.POST.get('list_type'))
            if is_free:
                del form.fields['payment_method']

        categoryform = category_form_class(
                        content_type,
                        request.POST,)

        if form.is_valid() and categoryform.is_valid():
            job = form.save(commit=False)
            pricing = form.cleaned_data['pricing']

            if require_payment and is_free:
                job.payment_method = 'paid - cc'

            # set it to pending if the user is anonymous or not an admin
            if not can_add_active:
                #job.status = 1
                job.status_detail = 'pending'

            # list types and duration
            if not job.requested_duration:
                job.requested_duration = 30
            if not job.list_type:
                job.list_type = 'regular'

            # set up all the times
            now = datetime.now()
            job.activation_dt = now
            if not job.post_dt:
                job.post_dt = now

            # set the expiration date
            job.expiration_dt = job.activation_dt + timedelta(
                                        days=job.requested_duration)

            # semi-anon job posts don't get a slug field on the form
            # see __init__ method in JobForm
            if not job.slug:
                #job.slug = get_job_unique_slug(slugify(job.title))
                job.slug = '%s-%s' % (slugify(job.title),
                                        object_type.objects.count())

            job = update_perms_and_save(request, form, job)

            # create invoice
            job_set_inv_payment(request.user, job, pricing)

            #setup categories
            category = Category.objects.get_for_object(job, 'category')
            sub_category = Category.objects.get_for_object(
                                                job, 'sub_category')

            ## update the category of the job
            category_removed = False
            category = categoryform.cleaned_data['category']
            if category != '0':
                Category.objects.update(job, category, 'category')
            else:  # remove
                category_removed = True
                Category.objects.remove(job, 'category')
                Category.objects.remove(job, 'sub_category')

            if not category_removed:
                # update the sub category of the job
                sub_category = categoryform.cleaned_data['sub_category']
                if sub_category != '0':
                    Category.objects.update(job, sub_category,
                                                'sub_category')
                else:  # remove
                    Category.objects.remove(job,'sub_category')

            #save relationships
            job.save()
            msg_string = 'Successfully added %s' % job
            messages.add_message(request, messages.SUCCESS,_(msg_string))

            # send notification to administrators
            recipients = get_notice_recipients(
                            'module', 'jobs', 'jobrecipients')
            if recipients:
                if notification:
                    extra_context = {
                        'object': job,
                        'request': request,
                    }
                    notification.send_emails(recipients, 'job_added',
                                                extra_context)

            # send user to the payment page if payment is required
            if require_payment:
                if job.payment_method.lower() in ['credit card', 'cc']:
                    if job.invoice and job.invoice.balance > 0:
                        return HttpResponseRedirect(reverse(
                            'payment.pay_online',
                            args=[job.invoice.id, job.invoice.guid])
                        )

            # send user to thank you or view page
            if request.user.profile.is_superuser:
                return HttpResponseRedirect(
                        reverse(success_redirect, args=[job.slug]))
            else:
                return HttpResponseRedirect(reverse(thankyou_redirect))
    else:
        # Redirect user w/perms to create pricing if none exist
        pricings = JobPricing.objects.all()
        if not pricings and has_perm(request.user, 'jobs.add_jobpricing'):
            msg_string = 'You need to add a %s Pricing before you can add a %s.' % (get_setting('module', 'jobs', 'label_plural'),get_setting('module', 'jobs', 'label'))
            messages.add_message(request, messages.WARNING, _(msg_string))
            return HttpResponseRedirect(reverse('job_pricing.add'))

        initial_category_form_data = {
            'app_label': 'jobs',
            'model': 'job',
            'pk': 0, #not used for this view but is required for the form
        }
        categoryform = category_form_class(
                        content_type,
                        initial=initial_category_form_data,)

    return render_to_response(template_name,
            {'form': form,
             'require_payment': require_payment,
             'categoryform': categoryform},
            context_instance=RequestContext(request))

Example 8

Project: virtmgr
Source File: views.py
View license
def index(request, host_id):

	if not request.user.is_authenticated():
		return HttpResponseRedirect('/user/login/')

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
                      type=type_err, 
                      message=msg, 
                      user_id=request.user.id
                      )
		error_msg.save()

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def vm_conn():
		flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
	  	auth = [flags, creds, None]
		uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
		try:
		   	conn = libvirt.openAuth(uri, auth, 0)
		   	return conn
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0

	def get_all_vm():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_info():
		try:
			info = []
			xml_inf = conn.getSysinfo(0)
			info.append(conn.getHostname())
			info.append(conn.getInfo()[0])
			info.append(conn.getInfo()[2])
			info.append(util.get_xml_path(xml_inf, "/sysinfo/processor/entry[6]"))
			return info
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_mem_usage():
		try:
			allmem = conn.getInfo()[1] * 1048576
			get_freemem = conn.getMemoryStats(-1,0)
			if type(get_freemem) == dict:
				freemem = (get_freemem.values()[0] + get_freemem.values()[2] + get_freemem.values()[3]) * 1024
				percent = (freemem * 100) / allmem
				percent = 100 - percent
				memusage = (allmem - freemem)
			else:
				memusage = None
				percent = None
			return allmem, memusage, percent
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_cpu_usage():
		try:
			prev_idle = 0
			prev_total = 0
			cpu = conn.getCPUStats(-1,0)
			if type(cpu) == dict:
				for num in range(2):
				        idle = conn.getCPUStats(-1,0).values()[1]
				        total = sum(conn.getCPUStats(-1,0).values())
				        diff_idle = idle - prev_idle
				        diff_total = total - prev_total
				        diff_usage = (1000 * (diff_total - diff_idle) / diff_total + 5) / 10
				        prev_total = total
				        prev_idle = idle
				        if num == 0: 
			        		time.sleep(1)
			        	else:
			        		if diff_usage < 0:
			        			diff_usage = 0
			else:
				diff_usage = None
			return diff_usage
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def get_dom(vname):
		try:
			dom = conn.lookupByName(vname)
			return dom
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	errors = []
		
	if request.method == 'POST':
		login_kvm = request.POST.get('login_kvm','')
		passwd_kvm = request.POST.get('passwd_kvm','')
		if login_kvm or passwd_kvm:
			request.session['login_kvm'] = login_kvm 
			request.session['passwd_kvm'] = passwd_kvm
			return HttpResponseRedirect('/overview/%s/' % (host_id))
		vname = request.POST.get('vname','')
		if vname:
			conn = vm_conn()
			dom = get_dom(vname)
		if request.POST.get('suspend',''):
			try:
				dom.suspend()
				msg = _('Suspend VM: ')
				msg = msg + vname
				add_error(msg, 'user')
			except libvirt.libvirtError as e:
				add_error(e, 'libvirt')
				msg = _('Error: VM alredy suspended')
				errors.append(msg)
		if request.POST.get('resume',''):
			try:
				dom.resume()
				msg = _('Resume VM: ')
				msg = msg + vname
				add_error(msg, 'user')
			except libvirt.libvirtError as e:
				add_error(e, 'libvirt')
				msg = _('Error: VM alredy resume')
				errors.append(msg)
		if request.POST.get('start',''):
			try:
				dom.create()
				msg = _('Start VM: ')
				msg = msg + vname
				add_error(msg, 'user')
			except libvirt.libvirtError as e:
				add_error(e, 'libvirt')
				msg = _('Error: VM alredy start')
				errors.append(msg)
		if request.POST.get('shutdown',''):
			try:
				dom.shutdown()
				msg = _('Shutdown VM: ')
				msg = msg + vname
				add_error(msg, 'user')
			except libvirt.libvirtError as e:
				add_error(e, 'libvirt')
				msg = _('Error: VM alredy shutdown')
				errors.append(msg)
		if request.POST.get('destroy',''):
			try:
				dom.destroy()
				msg = _('Force shutdown VM: ')
				msg = msg + vname
				add_error(msg, 'user')
			except libvirt.libvirtError as e:
				add_error(e, 'libvirt')
				msg = _('Error: VM alredy shutdown')
				errors.append(msg)
            
		if not errors:
			return HttpResponseRedirect('/overview/%s/' % (host_id))

	conn = vm_conn()

	if conn != "error":
		all_vm = get_all_vm()
		host_info = get_info()
		mem_usage = get_mem_usage()
		cpu_usage = get_cpu_usage()
		lib_virt_ver = conn.getLibVersion()
		conn_type = conn.getURI()
		conn.close()
	else:
		msg = _('Error connecting: Check the KVM login and KVM password')
		errors.append(msg)
		
	return render_to_response('overview.html', locals())

Example 9

Project: sublimall-server
Source File: views.py
View license
    @transaction.atomic
    def post(self, request):
        template = 'registration.html'

        current_user_count = Member.objects.all().count()
        if current_user_count >= settings.MAX_MEMBER:
            logger.warning('Max registration number reached')
            return render(
                request,
                template,
                {'form':
                    {'errors':
                        "Max member reach. I'm sorry about that, "
                        "don't forget that it's a beta version of Sublimall. "
                        "Registrations will been soon re-opened!"}})

        email = request.POST.get('email', '').lower()
        email2 = request.POST.get('email2', '').lower()
        password = request.POST.get('password')
        password2 = request.POST.get('password2')

        if not email:
            return render(
                request,
                template,
                {"form": {'errors': "Email can't be empty."}})
        if not password:
            return render(
                request,
                template,
                {"form": {'errors': "Password can't be empty."}})

        try:
            validate_email(email)
        except ValidationError:
            return render(
                request, template, {"form": {'errors': "Need a valid email."}})

        password_validation, error = is_password_valid(password)
        if not password_validation:
            return render(
                request,
                template,
                {"form": {"errors": error}})

        if password != password2:
            return render(
                request,
                template,
                {"form": {'errors': "Password doesn't match."}})

        if email != email2:
            return render(
                request,
                template,
                {"form": {'errors': "Emails doesn't match."}})

        if Member.objects.filter(email=email).exists():
            return render(
                request, template, {"form": {'errors': "Email already used."}})

        try:
            member = Member(email=email, is_active=False)
            member.set_password(password)
            member.full_clean()
            member.save()

            member.send_registration_confirmation()

        except Exception:
            logger.error(
                'Registration unhandled exception',
                exc_info=True,
                extra={'request': request})
            return render(
                request,
                template,
                {"form": {
                    'errors':
                    "Error while creating your account. "
                    "A report have been sent. Sorry about that."}})

        messages.success(
            request,
            "You'll receive an email soon, check it to confirm "
            "your account. See you soon!")
        return HttpResponseRedirect(reverse('login'))

Example 10

Project: virtmgr
Source File: views.py
View license
def pool(request, host_id, pool):

	if not request.user.is_authenticated():
		return HttpResponseRedirect('/')

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
			            type=type_err, 
			            message=msg, 
			            user_id=request.user.id
			            )
		error_msg.save()

	def get_storages():
		try:
			storages = {}
			for name in conn.listStoragePools():
				stg = conn.storagePoolLookupByName(name)
				status = stg.isActive()
				storages[name] = status
			for name in conn.listDefinedStoragePools():
				stg = conn.storagePoolLookupByName(name)
				status = stg.isActive()
				storages[name] = status
			return storages
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def vm_conn():
	   	try:
			flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
	  		auth = [flags, creds, None]
			uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
		   	conn = libvirt.openAuth(uri, auth, 0)
		   	return conn
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_vms():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0

	def get_conn_pool(pool):
		try:
			stg = conn.storagePoolLookupByName(pool)
			return stg
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def pool_start():
		try:
			stg.create(0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def pool_stop():
		try:
			stg.destroy()
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def pool_delete():
		try:
			stg.undefine()
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"
			
	def pool_refresh():
		try:
			stg.refresh(0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_stg_info(get):
		try:
			if get == "info":
				if stg.info()[3] == 0:
					percent = 0
				else:
					percent = (stg.info()[2] * 100) / stg.info()[1]
				stg_info = stg.info()
				stg_info.append(percent)
				return stg_info
			elif get == "status":
				return stg.isActive()
			elif get == "start":
				return stg.autostart()
			elif get == "list":
				return stg.listVolumes()
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_type():
		try:
			xml = stg.XMLDesc(0)
			return util.get_xml_path(xml, "/pool/@type")
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_target_path():
		try:
			xml = stg.XMLDesc(0)
			return util.get_xml_path(xml, "/pool/target/path")
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def delete_volume(img):
		try:
			vol = stg.storageVolLookupByName(img)
			vol.delete(0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def stg_set_autostart(pool):
		try:
			stg = conn.storagePoolLookupByName(pool)
			stg.setAutostart(1)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def create_volume(img, size_max):
		try:
			size_max = int(size_max) * 1073741824
			xml = """
				<volume>
					<name>%s.img</name>
					<capacity>%s</capacity>
					<allocation>0</allocation>
					<target>
						<format type='qcow2'/>
					</target>
				</volume>""" % (img, size_max)
			stg.createXML(xml,0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def create_stg_pool(name_pool, path_pool):
		try:
			xml = """
				<pool type='dir'>
					<name>%s</name>
						<target>
							<path>%s</path>
						</target>
				</pool>""" % (name_pool, path_pool)
			conn.storagePoolDefineXML(xml,0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def clone_volume(img, new_img):
		try:
			vol = stg.storageVolLookupByName(img)
			xml = """
				<volume>
					<name>%s</name>
					<capacity>0</capacity>
					<allocation>0</allocation>
					<target>
						<format type='qcow2'/>
					</target>
				</volume>""" % (new_img)
			stg.createXMLFrom(xml, vol, 0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_vl_info(listvol):
		try:
			volinfo = {}
			if stg.isActive() != 0:
				for name in listvol:
					vol = stg.storageVolLookupByName(name)
					xml = vol.XMLDesc(0)
					size = vol.info()[1]
					format = util.get_xml_path(xml, "/volume/target/format/@type")
	 				volinfo[name] = size,format
			return volinfo
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"
	
	conn = vm_conn()
	errors = []

	if conn == "error":
		return HttpResponseRedirect('/overview/%s/' % (host_id))

	pools = get_storages()
	all_vm = get_vms()
	
	if pool != 'new_stg_pool':
		stg = get_conn_pool(pool)
		status = get_stg_info('status')
		if status == 1:
			pool_refresh()
			info = get_stg_info('info')
			stype = get_type()
			spath = get_target_path()
			start = get_stg_info('start')
			listvol = get_stg_info('list')
			volinfo = get_vl_info(listvol)
			hdd_size = range(1,321)
		errors = []

	if request.method == 'POST':
		if request.POST.get('new_stg_pool',''):
			name_pool = request.POST.get('name_pool','')
			path_pool = request.POST.get('path_pool','')
			simbol = re.search('[^a-zA-Z0-9\_]+', name_pool)
			if len(name_pool) > 20:
				msg = _('The name of the storage pool must not exceed 20 characters')
				errors.append(msg)
			if simbol:
				msg = _('The name of the storage pool must not contain any characters and Russian characters')
				errors.append(msg)
			if not name_pool:
				msg = _('Enter the name of the pool')
				errors.append(msg)
			if not path_pool:
				msg = _('Enter the path of the pool')
				errors.append(msg)
			if not errors:
				if create_stg_pool(name_pool, path_pool) is "error":
					msg = _('Such a pool already exists')
					errors.append(msg)
				else:
					stg = get_conn_pool(name_pool)
					stg_set_autostart(name_pool)
					if pool_start() is "error":
						msg = _('Pool is created, but when I run the pool fails, you may specify the path does not exist')
						errors.append(msg)
						return HttpResponseRedirect('/storage/%s/%s/' % (host_id, name_pool))
					else:
						msg = _('Creating a storage pool: ')
						msg = msg + name_pool
						add_error(msg,'user')
						return HttpResponseRedirect('/storage/%s/%s/' % (host_id, name_pool))
				if errors:
					return render_to_response('storage.html', locals())
		if request.POST.get('stop_pool',''):
			pool_stop()
			msg = _('Stop storage pool: ')
			msg = msg + pool
			add_error(msg,'user')
			return HttpResponseRedirect('/storage/%s/%s/' % (host_id, pool))
		if request.POST.get('start_pool',''):
			pool_start()
			msg = _('Start storage pool: ')
			msg = msg + pool
			add_error(msg,'user')
			return HttpResponseRedirect('/storage/%s/%s/' % (host_id, pool))
		if request.POST.get('del_pool',''):
			pool_delete()
			msg = _('Delete storage pool: ')
			msg = msg + pool
			add_error(msg,'user')
			return HttpResponseRedirect('/storage/%s/' % (host_id))
		if request.POST.get('vol_del',''):
			img = request.POST['img']
			delete_volume(img)
			msg = _('Delete image: ')
			msg = msg + img
			add_error(msg,'user')
			return HttpResponseRedirect('/storage/%s/%s/' % (host_id, pool))
		if request.POST.get('vol_add',''):
			img = request.POST.get('img','')
			size_max = request.POST.get('size_max','')
			simbol = re.search('[^a-zA-Z0-9\_]+', img)
			if len(img) > 20:
				msg = _('The name of the images must not exceed 20 characters')
				errors.append(msg)
			if simbol:
				msg = _('The name of the image must not contain any characters and Russian characters')
				errors.append(msg)
			if not img:
				msg = _('Enter image name')
				errors.append(msg)
			if not size_max:
				msg = _('Enter image size')
				errors.append(msg)
			if not errors:
				create_volume(img, size_max)
				msg = _('Create image: ')
				msg = msg + img + '.img'
				add_error(msg,'user')
				return HttpResponseRedirect('/storage/%s/%s/' % (host_id, pool))
		if request.POST.get('vol_clone',''):
			img = request.POST.get('img','')
			new_img = request.POST.get('new_img','')
			simbol = re.search('[^a-zA-Z0-9\_]+', new_img)
			new_img = new_img + '.img'
			if new_img == '.img':
				msg = _('Enter image name')
				errors.append(msg)
			if len(new_img) > 20:
				msg = _('The name of the images must not exceed 20 characters')
				errors.append(msg)
			if simbol:
				msg = _('The name of the image must not contain any characters and Russian characters')
				errors.append(msg)
			if new_img in listvol:
				msg = _('The image of the same name already exists')
				errors.append(msg)
			if re.search('.ISO', img) or re.search('.iso', img):
				msg = _('You can only clone a virtual machine images')
				errors.append(msg)
			if not errors:
				clone_volume(img, new_img)
				msg = _('Cloning image: ')
				msg = msg + img + ' => ' + new_img
				add_error(msg,'user')
				return HttpResponseRedirect('/storage/%s/%s/' % (host_id, pool))

	conn.close()
				
	return render_to_response('storage.html', locals())

Example 11

Project: djangobb
Source File: views.py
View license
def search(request):
    # TODO: used forms in every search type

    def _render_search_form(form=None):
        return render(request, 'djangobb_forum/search_form.html', {'categories': Category.objects.all(),
                'form': form,
                })

    if not 'action' in request.GET:
        return _render_search_form(form=PostSearchForm())

    if request.GET.get("show_as") == "posts":
        show_as_posts = True
        template_name = 'djangobb_forum/search_posts.html'
    else:
        show_as_posts = False
        template_name = 'djangobb_forum/search_topics.html'

    context = {}

    # Create 'user viewable' pre-filtered topics/posts querysets
    viewable_category = Category.objects.all()
    topics = Topic.objects.all().order_by("-last_post__created")
    posts = Post.objects.all().order_by('-created')
    user = request.user
    if not user.is_superuser:
        user_groups = user.groups.all() or [] # need 'or []' for anonymous user otherwise: 'EmptyManager' object is not iterable
        viewable_category = viewable_category.filter(Q(groups__in=user_groups) | Q(groups__isnull=True))

        topics = Topic.objects.filter(forum__category__in=viewable_category)
        posts = Post.objects.filter(topic__forum__category__in=viewable_category)

    base_url = None
    _generic_context = True

    action = request.GET['action']
    if action == 'show_24h':
        date = timezone.now() - timedelta(days=1)
        if show_as_posts:
            context["posts"] = posts.filter(Q(created__gte=date) | Q(updated__gte=date))
        else:
            context["topics"] = topics.filter(Q(last_post__created__gte=date) | Q(last_post__updated__gte=date))
        _generic_context = False
    elif action == 'show_new':
        if not user.is_authenticated():
            raise Http404("Search 'show_new' not available for anonymous user.")
        try:
            last_read = PostTracking.objects.get(user=user).last_read
        except PostTracking.DoesNotExist:
            last_read = None

        if last_read:
            if show_as_posts:
                context["posts"] = posts.filter(Q(created__gte=last_read) | Q(updated__gte=last_read))
            else:
                context["topics"] = topics.filter(Q(last_post__created__gte=last_read) | Q(last_post__updated__gte=last_read))
            _generic_context = False
        else:
            #searching more than forum_settings.SEARCH_PAGE_SIZE in this way - not good idea :]
            topics_id = [topic.id for topic in topics[:forum_settings.SEARCH_PAGE_SIZE] if forum_extras.has_unreads(topic, user)]
            topics = Topic.objects.filter(id__in=topics_id) # to create QuerySet

    elif action == 'show_unanswered':
        topics = topics.filter(post_count=1)
    elif action == 'show_subscriptions':
        topics = topics.filter(subscribers__id=user.id)
    elif action == 'show_user':
        # Show all posts from user or topics started by user
        if not user.is_authenticated():
            raise Http404("Search 'show_user' not available for anonymous user.")

        user_id = request.GET.get("user_id", user.id)
        try:
            user_id = int(user_id)
        except ValueError:
            raise SuspiciousOperation()

        if user_id != user.id:
            try:
                search_user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                messages.error(request, _("Error: User unknown!"))
                return HttpResponseRedirect(request.path)
            messages.info(request, _("Filter by user '%(username)s'.") % {'username': search_user.username})

        if show_as_posts:
            posts = posts.filter(user__id=user_id)
        else:
            # show as topic
            topics = topics.filter(posts__user__id=user_id).order_by("-last_post__created").distinct()

        base_url = "?action=show_user&user_id=%s&show_as=" % user_id
    elif action == 'search':
        form = PostSearchForm(request.GET)
        if not form.is_valid():
            return _render_search_form(form)

        keywords = form.cleaned_data['keywords']
        author = form.cleaned_data['author']
        forum = form.cleaned_data['forum']
        search_in = form.cleaned_data['search_in']
        sort_by = form.cleaned_data['sort_by']
        sort_dir = form.cleaned_data['sort_dir']

        query = SearchQuerySet().models(Post)

        if author:
            query = query.filter(author__username=author)

        if forum != '0':
            query = query.filter(forum__id=forum)

        if keywords:
            if search_in == 'all':
                query = query.filter(SQ(topic=keywords) | SQ(text=keywords))
            elif search_in == 'message':
                query = query.filter(text=keywords)
            elif search_in == 'topic':
                query = query.filter(topic=keywords)

        order = {'0': 'created',
                 '1': 'author',
                 '2': 'topic',
                 '3': 'forum'}.get(sort_by, 'created')
        if sort_dir == 'DESC':
            order = '-' + order

        post_pks = query.values_list("pk", flat=True)

        if not show_as_posts:
            # TODO: We have here a problem to get a list of topics without double entries.
            # Maybe we must add a search index over topics?

            # Info: If whoosh backend used, setup HAYSTACK_ITERATOR_LOAD_PER_QUERY
            #    to a higher number to speed up
            context["topics"] = topics.filter(posts__in=post_pks).distinct()
        else:
            # FIXME: How to use the pre-filtered query from above?
            posts = posts.filter(pk__in=post_pks).order_by(order)
            context["posts"] = posts

        get_query_dict = request.GET.copy()
        get_query_dict.pop("show_as")
        base_url = "?%s&show_as=" % get_query_dict.urlencode()
        _generic_context = False

    if _generic_context:
        if show_as_posts:
            context["posts"] = posts.filter(topic__in=topics).order_by('-created')
        else:
            context["topics"] = topics

    if base_url is None:
        base_url = "?action=%s&show_as=" % action

    if show_as_posts:
        context['posts_page'] = get_page(context['posts'], request, forum_settings.SEARCH_PAGE_SIZE)
        context["as_topic_url"] = base_url + "topics"
        post_count = context["posts"].count()
        messages.success(request, _("Found %i posts.") % post_count)
    else:
        context['topics_page'] = get_page(context['topics'], request, forum_settings.SEARCH_PAGE_SIZE)
        context["as_post_url"] = base_url + "posts"
        topic_count = context["topics"].count()
        messages.success(request, _("Found %i topics.") % topic_count)

    return render(request, template_name, context)

Example 12

Project: django-templatesadmin
Source File: views.py
View license
@never_cache
@user_passes_test(lambda u: user_in_templatesadmin_group(u))
@login_required
def modify(request,
           path,
           template_name='templatesadmin/edit.html',
           base_form=TemplateForm,
           available_template_dirs=TEMPLATESADMIN_TEMPLATE_DIRS):

    template_path = _fixpath(path)

    # Check if file is within template-dirs
    if not any([template_path.startswith(templatedir) for templatedir in available_template_dirs]):
        request.user.message_set.create(message=_('Sorry, that file is not available for editing.'))
        return HttpResponseRedirect(reverse('templatesadmin-overview'))

    if request.method == 'POST':
        formclass = base_form
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(hook.contribute_to_form(template_path))

        form = formclass(request.POST)
        if form.is_valid():
            content = form.cleaned_data['content']

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    pre_save_notice = hook.pre_save(request, form, template_path)
                    if pre_save_notice:
                        request.user.message_set.create(message=pre_save_notice)
            except TemplatesAdminException, e:
                request.user.message_set.create(message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            # Save the template
            try:
                f = open(template_path, 'r')
                file_content = f.read()
                f.close()

                # browser tend to strip newlines from <textarea/>s before
                # HTTP-POSTing: re-insert them if neccessary

                # content is in dos-style lineending, will be converted in next step
                if (file_content[-1] == '\n' or file_content[:-2] == '\r\n') \
                   and content[:-2] != '\r\n':
                    content = u"%s\r\n" % content

                # Template is saved in unix-style, save in unix style.
                if None == search("\r\n", file_content):
                    content = content.replace("\r\n", "\n")

                f = codecs.open(template_path, 'w', 'utf-8')
                f.write(content)
                f.close()
            except IOError, e:
                request.user.message_set.create(
                    message=_('Template "%(path)s" has not been saved! Reason: %(errormsg)s' % {
                        'path': path,
                        'errormsg': e
                    })
                )
                return HttpResponseRedirect(request.build_absolute_uri())

            try:
                for hook in TEMPLATESADMIN_EDITHOOKS:
                    post_save_notice = hook.post_save(request, form, template_path)
                    if post_save_notice:
                        request.user.message_set.create(message=post_save_notice)
            except TemplatesAdminException, e:
                request.user.message_set.create(message=e.message)
                return HttpResponseRedirect(request.build_absolute_uri())

            request.user.message_set.create(
                message=_('Template "%s" was saved successfully.' % path)
            )
            return HttpResponseRedirect(reverse('templatesadmin-overview'))
    else:
        template_file = codecs.open(template_path, 'r', 'utf-8').read()

        formclass = TemplateForm
        for hook in TEMPLATESADMIN_EDITHOOKS:
            formclass.base_fields.update(hook.contribute_to_form(template_path))

        form = formclass(
            initial={'content': template_file}
        )

    template_context = {
        'messages': request.user.get_and_delete_messages(),
        'form': form,
        'short_path': path,
        'template_path': path,
        'template_writeable': os.access(template_path, os.W_OK),
        'ADMIN_MEDIA_PREFIX': settings.ADMIN_MEDIA_PREFIX,
    }

    return render_to_response(template_name, template_context,
                              RequestContext(request))

Example 13

Project: readthedocs.org
Source File: views.py
View license
def create_profile(request, form_class, success_url=None,
                   template_name='profiles/private/create_profile.html',
                   extra_context=None):
    """
    Create a profile for the current user, if one doesn't already
    exist.

    If the user already has a profile, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view.

    **Optional arguments:**

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``form_class``
        The form class to use for validating and creating the user
        profile. This form class must define a method named
        ``save()``, implementing the same argument signature as the
        ``save()`` method of a standard Django ``ModelForm`` (this
        view will call ``save(commit=False)`` to obtain the profile
        object, and fill in the user before the final save). If the
        profile object includes many-to-many relations, the convention
        established by ``ModelForm`` of using a method named
        ``save_m2m()`` will be used, and so your form class should
        also define this method.

    ``success_url``
        The URL to redirect to after successful profile creation. If
        this argument is not supplied, this will default to the URL of
        :view:`profiles.views.profile_detail` for the newly-created
        profile object.

    ``template_name``
        The template to use when displaying the profile-creation
        form. If not supplied, this will default to
        :template:`profiles/create_profile.html`.

    **Context:**

    ``form``
        The profile-creation form.

    **Template:**

    ``template_name`` keyword argument, or
    :template:`profiles/create_profile.html`.

    """
    try:
        profile_obj = request.user.profile
        return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass

    #
    # We set up success_url here, rather than as the default value for
    # the argument. Trying to do it as the argument's default would
    # mean evaluating the call to reverse() at the time this module is
    # first imported, which introduces a circular dependency: to
    # perform the reverse lookup we need access to profiles/urls.py,
    # but profiles/urls.py in turn imports this module.
    #

    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={'username': request.user.username})
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            profile_obj = form.save(commit=False)
            profile_obj.user = request.user
            profile_obj.save()
            if hasattr(form, 'save_m2m'):
                form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)

Example 14

Project: django-simplesurvey
Source File: views.py
View license
def submit(request):
    
    if request.method == 'POST':
        
        question_set_id = request.POST.get('question_set', '')
        answer_set_id = request.POST.get('answer_set', None)
        
        try:
        
            user = request.user.is_authenticated() and request.user or None
            question_set = QuestionSet.objects.get(slug=question_set_id)
            related = _object_from_contenttype(request.POST.get('related', None))
            
            if not user and not question_set.allow_anonymous:
                raise Http404, "Anonymous users are not allowed to submit answers"
                
            if user and not question_set.allow_multiple_responses:

                qs = AnswerSet.objects.filter(question_set=question_set, user=user)
                if related:
                    qs = qs.filter(content_type=related.content_type, object_id=related.pk)
                count = qs.count()

                if count > 0 and not answer_set_id:
                    raise Http404, "This survey can be completed only once per user"
            
            form = SurveyForm(question_set, request.POST)
            
            if form.is_valid():
                
                if answer_set_id and user:
                    
                    answer_set = AnswerSet.objects.get(pk=answer_set_id)
                    
                else:
                    
                    answer_set = AnswerSet(
                        question_set=question_set,
                        user=user
                    )
                
                    if related:
                        answer_set.related_object = related
                    
                    answer_set.save()
                
                for k, v in form.cleaned_data.items():
                    
                    if k.startswith("answer_for_"):
                        
                        try:
                        
                            question = Question.objects.get(pk=k[11:], question_set=question_set)
                            
                            if question.type == 'C':
                              v = "|".join(v)
                            
                            try:
                            
                                answer = answer_set.answers.get(question=question)
                                answer.text = v
                                
                            except Answer.DoesNotExist:
                        
                                answer = Answer(
                                    question=question,
                                    answer_set=answer_set,
                                    text=v
                                )
                            
                            answer.save()
                            
                        except Question.DoesNotExist:
                            pass
                            
                return HttpResponseRedirect(
                    getattr(settings, 'SIMPLESURVEY_COMPLETE_REDIRECT', '/survey/complete/'))
                
            else:
                invalid_callback = getattr(settings, "SIMPLESURVEY_INVALID_CALLBACK", None)
                if invalid_callback:
                    return invalid_callback(request, form, question_set, related)
                return HttpResponse("ERROR: All fields are required")
            
        except QuestionSet.DoesNotExist:
            raise Http404, "question set does not exist"

Example 15

Project: virtmgr
Source File: views.py
View license
def pool(request, host_id, pool):

	if not request.user.is_authenticated():
		return HttpResponseRedirect('/')

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
			            type=type_err, 
			            message=msg, 
			            user_id=request.user.id
			            )
		error_msg.save()

	def get_vms():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_networks():
		try:
			networks = {}
			for name in conn.listNetworks():
				net = conn.networkLookupByName(name)
				status = net.isActive()
				networks[name] = status
			for name in conn.listDefinedNetworks():
				net = conn.networkLookupByName(name)
				status = net.isActive()
				networks[name] = status
			return networks
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def vm_conn():
		try:
			flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
			auth = [flags, creds, None]
			uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
			conn = libvirt.openAuth(uri, auth, 0)
			return conn
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0
			
	def get_conn_pool(pool):
		try:
			net = conn.networkLookupByName(pool)
			return net
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def pool_start():
		try:
			net.create()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def pool_stop():
		try:
			net.destroy()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def pool_delete():
		try:
			net.undefine()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def net_set_autostart(pool):
		try:
			net = conn.networkLookupByName(pool)
			net.setAutostart(1)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_net_info(get):
		try:
			if get == "bridge":
				return net.bridgeName()
			elif get == "status":
				return net.isActive()
			elif get == "start":
				return net.autostart()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_ipv4_net():
		try:
			net = conn.networkLookupByName(pool)
			xml = net.XMLDesc(0)
			addrStr = util.get_xml_path(xml, "/network/ip/@address")
			netmaskStr = util.get_xml_path(xml, "/network/ip/@netmask")

			netmask = IP(netmaskStr)
			gateway = IP(addrStr)

			network = IP(gateway.int() & netmask.int())
			return IP(str(network) + "/" + netmaskStr)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_ipv4_dhcp_range():
		try:
			net = conn.networkLookupByName(pool)
			xml = net.XMLDesc(0)
			dhcpstart = util.get_xml_path(xml, "/network/ip/dhcp/range[1]/@start")
			dhcpend = util.get_xml_path(xml, "/network/ip/dhcp/range[1]/@end")
			if not dhcpstart or not dhcpend:
				return None
			
			return [IP(dhcpstart), IP(dhcpend)]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_ipv4_forward():
		try:
			xml = net.XMLDesc(0)
			fw = util.get_xml_path(xml, "/network/forward/@mode")
			forwardDev = util.get_xml_path(xml, "/network/forward/@dev")
			return [fw, forwardDev]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def create_net_pool(name_pool, forward, ipaddr, netmask, dhcp, s_dhcp, e_dhcp):
		try:
			xml = """
				<network>
					<name>%s</name>""" % (name_pool)

			if forward == "nat" or "route":
				xml += """<forward mode='%s'/>""" % (forward)

			xml += """<bridge stp='on' delay='0' />
						<ip address='%s' netmask='%s'>""" % (gw_ipaddr, netmask)

			if dhcp == "yes":
				xml += """<dhcp>
							<range start='%s' end='%s' />
						</dhcp>""" % (s_dhcp, e_dhcp)
					
			xml += """</ip>
				</network>"""
			conn.networkDefineXML(xml)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	conn = vm_conn()

	if conn == None:
		return HttpResponseRedirect('/overview/%s/' % (host_id))

	pools = get_networks()
	all_vm = get_vms()
	errors = []

	if pool != 'new_net_pool':
		net = get_conn_pool(pool)
		bridge = get_net_info('bridge')
		status = get_net_info('status')
		if status == 1:
			start = get_net_info('start')
			network = get_ipv4_net()
			dhcprange = get_ipv4_dhcp_range()
			netmode = get_ipv4_forward()

	if request.method == 'POST':
		if request.POST.get('new_net_pool',''):
			name_pool = request.POST.get('name_pool','')
			net_addr = request.POST.get('net_addr','')
			forward = request.POST.get('forward','')
			dhcp = request.POST.get('dhcp','')
			simbol = re.search('[^a-zA-Z0-9\_]+', name_pool)
			if len(name_pool) > 20:
				msg = _('The name of the network pool must not exceed 20 characters')
				errors.append(msg)
			if simbol:
				msg = _('The name of the network pool must not contain any characters and Russian characters')
				errors.append(msg)
			if not name_pool:
				msg = _('Enter the name of the pool')
				errors.append(msg)
			if not net_addr:
				msg = _('Enter the IP subnet')
				errors.append(msg)
			try:
				netmask = IP(net_addr).strNetmask()
				ipaddr = IP(net_addr)
				gw_ipaddr = ipaddr[1].strNormal()
				start_dhcp = ipaddr[2].strNormal()
				end_dhcp = ipaddr[254].strNormal()
			except:
				msg = _('IP subnet must be 192.168.1.0/24 or 192.168.1.0/26')
				errors.append(msg)
			if errors:
				return render_to_response('network.html', locals())
			if not errors:
				if create_net_pool(name_pool, forward, gw_ipaddr, netmask, dhcp, start_dhcp, end_dhcp) is "error":
					msg = _('Such a pool already exists')
					errors.append(msg)
				if not errors:
					net_set_autostart(name_pool)
					net = get_conn_pool(name_pool)
					if pool_start() is "error":
						msg = _('Pool is created, but when I run the pool fails, you may specify an existing network')
						errors.append(msg)
					else:
						msg = _('Creating a network pool: ') 
						msg = msg + name_pool
						add_error(msg, 'user')
						return HttpResponseRedirect('/network/%s/%s/' % (host_id, name_pool))
					if errors:
						return render_to_response('network.html', locals())
		if request.POST.get('stop_pool',''):
			msg = _('Stop network pool: ')
			msg = msg + pool
			pool_stop()
			add_error(msg, 'user')
		if request.POST.get('start_pool',''):
			msg = _('Start network pool: ')
			msg = msg + pool
			pool_start()
			add_error(msg, 'user')
		if request.POST.get('del_pool',''):
			msg = _('Delete network pool: ')
			msg = msg + pool
			pool_delete()
			add_error(msg, 'user')
			return HttpResponseRedirect('/network/%s/' % (host_id))
		return HttpResponseRedirect('/network/%s/%s/' % (host_id, pool))

	conn.close()

	return render_to_response('network.html', locals())

Example 16

Project: tendenci
Source File: views.py
View license
def index(request, form_class=SubmitContactForm, template_name="form.html"):

    if request.method == "GET":
        # event-log view
        EventLog.objects.log(instance=Contact(), action='viewed')

    if request.method == "POST":
        event_log_dict = {}
        form = form_class(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')

            if listed_in_email_block(email):
                # listed in the email blocks - it's a spam email we want to block
                # log the spam
                EventLog.objects.log()

                # redirect normally so they don't suspect
                return HttpResponseRedirect(reverse('form.confirmation'))

            address = form.cleaned_data.get('address')
            city = form.cleaned_data.get('city')
            state = form.cleaned_data.get('state')
            zipcode = form.cleaned_data.get('zipcode')
            country = form.cleaned_data.get('country')
            phone = form.cleaned_data.get('phone')
            url = form.cleaned_data.get('url')
            message = form.cleaned_data.get('message')

            exists = User.objects.filter(
                first_name__iexact=first_name,
                last_name__iexact=last_name,
                email__iexact=email,
            ).exists()

            if request.user.is_anonymous():
                username = first_name.replace(' ', '')
                if last_name:
                    username = username + '_' + last_name.replace(' ', '')
                username = username.lower()
                try:
                    User.objects.get(username=username)
                    x = User.objects.filter(first_name=first_name).count()
                    username = username + '_' + unicode(x)
                except User.DoesNotExist:
                    pass

                contact_user = User(
                    username=username,
                    email=email,
                    first_name=first_name,
                    last_name=last_name,
                )

                contact_user.is_active = False
                contact_user.save()
                profile = Profile(user=contact_user, owner=contact_user, creator=User.objects.get(pk=1),
                                  address=address, country=country, city=city, state=state,
                                  url=url, phone=phone, zipcode=zipcode)
                profile.save()
                sf_id = create_salesforce_contact(profile)

                # if exists:
                #     event_log_dict['description'] = 'logged-out submission as existing user'
                # else:
                event_log_dict['description'] = 'logged-out submission as new user'

            else:  # logged in user
                self_submit = all([
                    request.user.first_name.lower().strip() == first_name.lower().strip(),
                    request.user.last_name.lower().strip() == last_name.lower().strip(),
                    request.user.email.lower().strip() == email.lower().strip(),
                ])

                contact_user = request.user

                if exists:
                    if self_submit:
                        event_log_dict['description'] = 'logged-in submission as self'
                    else:
                        event_log_dict['description'] = 'logged-in submission as existing user'
                else:
                    event_log_dict['description'] = 'logged-in submission as non-existing user'

            contact_kwargs = {
                'first_name': first_name,
                'last_name': last_name,
                'message': message,
                'user': contact_user,
            }

            contact = Contact(**contact_kwargs)
            contact.allow_anonymous_view = False
            contact.save()

            if address or city or state or zipcode or country:
                address_kwargs = {
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                }
                obj_address = Address(**address_kwargs)
                obj_address.save()  # saves object
                contact.addresses.add(obj_address)  # saves relationship

            if phone:
                obj_phone = Phone(number=phone)
                obj_phone.save()  # saves object
                contact.phones.add(obj_phone)  # saves relationship

            if email:
                obj_email = Email(email=email)
                obj_email.save()  # saves object
                contact.emails.add(obj_email)  # saves relationship

            if url:
                obj_url = URL(url=url)
                obj_url.save()  # saves object
                contact.urls.add(obj_url)  # saves relationship

            site_name = get_setting('site', 'global', 'sitedisplayname')
            message_link = get_setting('site', 'global', 'siteurl')

            # send notification to administrators
            # get admin notice recipients
            recipients = get_notice_recipients('module', 'contacts', 'contactrecipients')
            if recipients:
                if notification:
                    extra_context = {
                    'reply_to': email,
                    'contact': contact,
                    'first_name': first_name,
                    'last_name': last_name,
                    'address': address,
                    'city': city,
                    'state': state,
                    'zipcode': zipcode,
                    'country': country,
                    'phone': phone,
                    'email': email,
                    'url': url,
                    'message': message,
                    'message_link': message_link,
                    'site_name': site_name,
                    }
                    notification.send_emails(recipients, 'contact_submitted', extra_context)

            # event-log (logged in)
            event_log = EventLog.objects.log(
                instance=contact,
                user=contact_user,
                action='submitted',
                **event_log_dict
            )

            event_log.url = contact.get_absolute_url()
            event_log.save()

            return HttpResponseRedirect(reverse('form.confirmation'))
        else:
            return render_to_response(template_name, {'form': form},
                context_instance=RequestContext(request))

    form = form_class()
    return render_to_response(template_name, {'form': form},
        context_instance=RequestContext(request))

Example 17

Project: django-adminactions
Source File: merge.py
View license
def merge(modeladmin, request, queryset):  # noqa
    """
    Merge two model instances. Move all foreign keys.

    """

    opts = modeladmin.model._meta
    perm = "{0}.{1}".format(opts.app_label, get_permission_codename('adminactions_merge', opts))
    if not request.user.has_perm(perm):
        messages.error(request, _('Sorry you do not have rights to execute this action'))
        return

    def raw_widget(field, **kwargs):
        """ force all fields as not required"""
        kwargs['widget'] = TextInput({'class': 'raw-value'})
        return field.formfield(**kwargs)

    merge_form = getattr(modeladmin, 'merge_form', MergeForm)
    MForm = modelform_factory(modeladmin.model,
                              form=merge_form,
                              exclude=('pk', ),
                              formfield_callback=raw_widget)
    OForm = modelform_factory(modeladmin.model,
                              exclude=('pk', ),
                              formfield_callback=raw_widget)

    tpl = 'adminactions/merge.html'
    # transaction_supported = model_supports_transactions(modeladmin.model)
    ctx = {
        '_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
        'transaction_supported': 'Un',
        'select_across': request.POST.get('select_across') == '1',
        'action': request.POST.get('action'),
        'fields': [f for f in queryset.model._meta.fields if not f.primary_key and f.editable],
        'app_label': queryset.model._meta.app_label,
        'result': '',
        'opts': queryset.model._meta}

    if 'preview' in request.POST:
        master = queryset.get(pk=request.POST.get('master_pk'))
        original = clone_instance(master)
        other = queryset.get(pk=request.POST.get('other_pk'))
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        with transaction.nocommit():
            form = MForm(request.POST, instance=master)
            other.delete()
            form_is_valid = form.is_valid()
        if form_is_valid:
            ctx.update({'original': original})
            tpl = 'adminactions/merge_preview.html'
        else:
            master = queryset.get(pk=request.POST.get('master_pk'))
            other = queryset.get(pk=request.POST.get('other_pk'))

    elif 'apply' in request.POST:
        master = queryset.get(pk=request.POST.get('master_pk'))
        other = queryset.get(pk=request.POST.get('other_pk'))
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        with transaction.nocommit():
            form = MForm(request.POST, instance=master)
            stored_pk = other.pk
            other.delete()
            ok = form.is_valid()
            other.pk = stored_pk
        if ok:
            if form.cleaned_data['dependencies'] == MergeForm.DEP_MOVE:
                related = api.ALL_FIELDS
            else:
                related = None
            fields = form.cleaned_data['field_names']
            api.merge(master, other, fields=fields, commit=True, related=related)
            return HttpResponseRedirect(request.path)
        else:
            messages.error(request, form.errors)
    else:
        try:
            master, other = queryset.all()
            # django 1.4 need to remove the trailing milliseconds
            for field in master._meta.fields:
                if isinstance(field, models.DateTimeField):
                    for target in (master, other):
                        raw_value = getattr(target, field.name)
                        if raw_value:
                            fixed_value = datetime(
                                raw_value.year,
                                raw_value.month,
                                raw_value.day,
                                raw_value.hour,
                                raw_value.minute,
                                raw_value.second)
                            setattr(target, field.name, fixed_value)
        except ValueError:
            messages.error(request, _('Please select exactly 2 records'))
            return

        initial = {'_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
                   'select_across': 0,
                   'generic': MergeForm.GEN_IGNORE,
                   'dependencies': MergeForm.DEP_MOVE,
                   'action': 'merge',
                   'master_pk': master.pk,
                   'other_pk': other.pk}
        formset = formset_factory(OForm)(initial=[model_to_dict(master), model_to_dict(other)])
        form = MForm(initial=initial, instance=master)

    adminForm = helpers.AdminForm(form, modeladmin.get_fieldsets(request), {}, [], model_admin=modeladmin)
    media = modeladmin.media + adminForm.media
    ctx.update({'adminform': adminForm,
                'formset': formset,
                'media': mark_safe(media),
                'action_short_description': merge.short_description,
                'title': u"%s (%s)" % (
                    merge.short_description.capitalize(),
                    smart_text(modeladmin.opts.verbose_name_plural),
                ),
                'master': master,
                'other': other})
    if django.VERSION[:2] > (1, 7):
        ctx.update(modeladmin.admin_site.each_context(request))
    else:
        ctx.update(modeladmin.admin_site.each_context())
    if django.VERSION[:2] > (1, 8):
        return render(request, tpl, context=ctx)
    else:
        return render_to_response(tpl, RequestContext(request, ctx))

Example 18

Project: WIPSTER
Source File: views.py
View license
def upload_form(request):

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
#            handle_uploaded_file(request.FILES['file'])
#            newsample = Sample(sample = request.FILES['sample'])
            f = request.FILES['sample']

            
            newsample = Sample(
                sample = f,
                ticket = request.POST['ticket'],
                filename = f.name,
                size = f.size,
#                type = f.content_type,
                type = handler.get_filetype(f),
                md5 = handler.get_md5(f),
                sha1 = handler.get_sha1(f),
                sha256 = handler.get_sha256(f),
                fuzzy = handler.get_fuzzy(f),
            )
            #breakdebug
            newsample.save()

            #Do post-processing stuff here
            s = Sample.objects.filter().order_by('-id')[0]
            #s.exif = handler.get_exif(s.sample).encode('ascii', errors='replace')
            #s.exif = unicode(handler.get_exif(s.sample))
            s.exif = handler.get_exif(s.sample)
            
            s.strings = handler.get_strings(s.sample)
            s.balbuzard = handler.get_balbuzard(s.sample)
            s.trid = handler.get_trid(s.sample)

            #SSDEEP/Fuzzy hash comparison
            s.ssdeep_compare = handler.ssdeep_compare(s.fuzzy, s.md5)

            #VirusTotal Search
            vt_res, vt_short_res = handler.get_vt(s.md5)
            if vt_res:
                s.vt = vt_res
                s.vt_short = vt_short_res

            #If EXE file, run EXE-specific checks
            if "PE32" and "Windows" in s.type:
                s.peframe = handler.get_peframe(s.sample)
                s.pescanner = handler.get_pescanner(s.sample)

            #If PDF file, run PDF-specific checks
            if "PDF" in s.type:
                s.pdfid = handler.get_pdfid(s.sample)
                s.peepdf = handler.get_peepdf(s.sample)
                s.pdf_strings = handler.get_pdfstrings(s.sample)

            #If DOC file, run DOC-specific checks
            if "Document File V2" in s.type:
                s.oleid = handler.get_oleid(s.sample)
                #If valid OLE file, run OLEMETA
                olematch = re.compile(r'\|\s+OLE format\s+\|\s+True\s+\|')
                if olematch.search(s.oleid):
                    s.olemeta = handler.get_olemeta(s.sample)
                #If VBA code detected, run OLEVBA
                vbamatch = re.compile(r'\|\s+VBA Macros\s+\|\s+True\s+\|')
                if vbamatch.search(s.oleid):
                    s.olevba = handler.get_olevba(s.sample)

            #If RTF file, run RTFOBJ
            if "Rich Text Format" in s.type:
                rtfobj, rtflist = handler.get_rtfobj(s.sample)
                s.rtfobj = rtfobj

            #If Objects found, run strings/balbuzard against them
            #REMOVED - TOO RESOURCE-INTENSIVE
#            if rtflist:
#                s.rtfobj_str = handler.get_rtfobj_str(rtflist)
#                s.rtfobj_balbuz = handler.get_rtfobj_balbuz(rtflist)
            
            

            s.save()

            newpage = "/sanalysis/md5/" + s.md5 + "/?upload=True"

            return HttpResponseRedirect(newpage)
        else:
            form = UploadFileForm()
            sample = Sample.objects.filter(created__lte=timezone.now()).order_by('-id')[:25]
            return render(request, 'sanalysis/upload_form.html', {'form': form, 'sample': sample},
                            context_instance = RequestContext(request))

#            return HttpResponseRedirect('/sanalysis/')

#            return render(request, 'sanalysis/sample_page.html', {'sample': sample,
#                                                                  'savename': savename,
#                                                                  'ta_use': ta_use,
#                                                                  'ta_analyses': ta_analyses,
#                                                                  'ta_risks': ta_risks,
#                                                                  'ta_network': ta_network,
#                                                                  'ta_ips': ta_ips,
#                                                                  'ta_domains': ta_domains,
#                                                                  'ta_commands': ta_commands,
#                                                                  'ta_submit': ta_submit,
#                                                                  'crits_use': crits_use,
#                                                                  'crits': crits_dict,
#                                                                  'crits_submit': crits_submit, })


    else:
        form = UploadFileForm()
        sample = Sample.objects.filter(created__lte=timezone.now()).order_by('-id')[:25]
        return render(request, 'sanalysis/upload_form.html', {'form': form, 'sample': sample})

Example 19

Project: django-yarr
Source File: views.py
View license
@login_required
def entry_state(
    request, feed_pk=None, entry_pk=None, state=None, if_state=None,
    template="yarr/confirm.html",
):
    """
    Change entry state for an entry, a feed, or all entries
    """
    # Filter entries by selection
    qs = models.Entry.objects.user(request.user)
    if entry_pk is not None:
        # Changing specific entry
        qs = qs.filter(pk=entry_pk)
        
    elif state == ENTRY_READ:
        if feed_pk is not None:
            # Changing all entries in a feed
            qs = qs.filter(feed__pk=feed_pk)
            
        # Only mark unread as read - don't change saved
        qs = qs.unread()
        
    else:
        # Either unknown state, or trying to bulk unread/save
        messages.error(request, 'Cannot perform this operation')
        return HttpResponseRedirect(reverse(home))
        
    # Check for if_state
    if if_state is not None:
        if if_state == ENTRY_UNREAD:
            qs = qs.unread()
        elif if_state == ENTRY_READ:
            qs = qs.read()
        elif if_state == ENTRY_SAVED:
            qs = qs.saved()
        else:
            messages.error(request, 'Unknown condition')
            return HttpResponseRedirect(reverse(home))
        
    # Check there's something to change
    count = qs.count()
    if count == 0:
        messages.error(request, 'No entries found to change')
        return HttpResponseRedirect(reverse(home))
    
    # Process
    if request.POST:
        # Change state and update unread count
        qs.set_state(state)
        
        # If they're not marked as read, they can't ever expire
        # If they're marked as read, they will be given an expiry date
        # when Feed._update_entries determines they can expire
        if state != ENTRY_READ:
            qs.clear_expiry()
        
        if state is ENTRY_UNREAD:
            messages.success(request, 'Marked as unread')
        elif state is ENTRY_READ:
            messages.success(request, 'Marked as read')
        elif state is ENTRY_SAVED:
            messages.success(request, 'Saved')
        return HttpResponseRedirect(reverse(home))
    
    # Prep messages
    op_text = {
        'verb': 'mark',
        'desc': '',
    }
    if state is ENTRY_UNREAD:
        op_text['desc'] = ' as unread'
    elif state is ENTRY_READ:
        op_text['desc'] = ' as read'
    elif state is ENTRY_SAVED:
        op_text['verb'] = 'save'
        
    if entry_pk:
        title = '%(verb)s item%(desc)s'
        msg = 'Are you sure you want to %(verb)s this item%(desc)s?'
    elif feed_pk:
        title = '%(verb)s feed%(desc)s'
        msg = 'Are you sure you want to %(verb)s all items in the feed%(desc)s?'
    else:
        title = '%(verb)s all items%(desc)s'
        msg = 'Are you sure you want to %(verb)s all items in every feed%(desc)s?'
    
    title = title % op_text
    title = title[0].upper() + title[1:]
    
    return render(request, template, {
        'title':    title,
        'message':  msg % op_text,
        'submit_label': title,
    })

Example 20

Project: RatticWeb
Source File: views.py
View license
@rattic_staff_required
def import_process(request, import_id):
    # If there was no session data, return 404
    if 'imported_data' not in request.session.keys():
        raise Http404

    # Get the entry we are concerned with
    try:
        entry = request.session['imported_data']['entries'][int(import_id)]
    except IndexError:
        raise Http404

    # Get the group
    groupid = request.session['imported_data']['group']
    try:
        group = Group.objects.get(pk=groupid)
    except Group.DoesNotExist:
        del request.session['imported_data']
        raise Http404

    if request.method == 'POST':
        # Try and import what we have now

        # Did the user upload a new attachment
        if entry['filename'] and 'attachment' not in request.FILES.keys():
            sfile = SimpleUploadedFile(entry['filename'], bytes(entry['filecontent']))
            request.FILES['attachment'] = sfile

        # Build the form
        form = CredForm(request.user, request.POST, request.FILES)

        # Do we have enough data to save?
        if form.is_valid():

            # Save the credential
            form.save()

            # Write the audit log
            CredAudit(
                audittype=CredAudit.CREDADD,
                cred=form.instance,
                user=request.user,
            ).save()

            # Remove the entry we're importing
            del request.session['imported_data']['entries'][int(import_id)]
            request.session.save()

            # Go back to the overview
            return HttpResponseRedirect(reverse('staff.views.import_overview'))

    else:
        # Init the cred, and create the form
        processed = dict(entry)

        # Create all the tags
        tlist = []
        for t in processed['tags']:
            (tag, create) = Tag.objects.get_or_create(name=t)
            tlist.append(tag)
        processed['tags'] = tlist

        # Setup the group
        processed['group'] = group

        # If the icon is empty set it
        if 'iconname' not in processed.keys():
            processed['iconname'] = 'Key.png'

        # Remove the attachment
        if processed['filename']:
            del processed['filename']
            del processed['filecontent']

        # Create the form
        form = CredForm(request.user, processed, {})

    return render(request, 'staff_import_process.html', {
        'form': form,
        'icons': get_icon_list(),
    })

Example 21

Project: coursys
Source File: views.py
View license
@requires_discipline_user
def edit_case_info(request, course_slug, case_slug, field):
    """
    View function for all of the "edit this aspect of the case" steps.  Uses the STEP_* dictionaries to get relevant strings/classes.
    """
    course = get_object_or_404(CourseOffering, slug=course_slug)
    case = get_object_or_404(DisciplineCaseBase, slug=case_slug, offering__slug=course_slug)
    case = case.subclass()

    # permisson checks
    roles = request.session['discipline-'+course_slug]
    if not case.can_edit(field):
        # once instructor finished, don't allow editing those fields
        return ForbiddenResponse(request, "letter has been sent: cannot edit this field")
    elif isinstance(case, DisciplineCaseInstr) and "INSTR" not in roles:
        # only instructor can edit those fields
        return ForbiddenResponse(request, "only the instructor can edit this field")
    elif isinstance(case, DisciplineCaseChair) and "DEPT" not in roles:
        # only discipline admins can edit chair fields
        return ForbiddenResponse(request, "only the Chair (or delegate) can edit this field")

    FormClass = STEP_FORM[field]
    if request.method == 'POST':
        form = FormClass(request.POST, instance=case)
        if form.is_valid():
            c = form.save()
            if field in PRE_LETTER_STEPS:
                # letter hasn't been reviewed if anything changes
                c.letter_review = False
                c.letter_sent = 'WAIT'
                c.penalty_implemented = False
                c.save()

            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("edit discipline case %s in %s: changed %s") % (c.slug, c.offering, STEP_DESC[field]),
                  related_object=c)
            l.save()
            messages.add_message(request, messages.SUCCESS, "Updated " + STEP_DESC[field] + '.')
            
            # set identical value for group members as requested
            also_contact = []
            for postfield in request.POST:
                match = also_set_re.match(postfield)
                if not match or request.POST[postfield] != "on":
                    continue
                
                field = match.group('field')
                caseid = match.group('caseid')
                cases = DisciplineCaseBase.objects.filter(id=caseid)
                if len(cases) != 1 or cases[0].group != case.group:
                    continue
                c0 = cases[0].subclass()
                if not c0.can_edit(field):
                    messages.add_message(request, messages.ERROR,
                        "Case for %s is finished: cannot update %s." % (c0.student.name(), STEP_DESC[field]))
                    continue

                if field=="contacted" and form.cleaned_data[field]=='MAIL':
                    # special case handled below
                    also_contact.append(c0)
                else:
                    setattr(c0, field, form.cleaned_data[field])
                    if field in PRE_LETTER_STEPS:
                        c0.letter_review = False
                    c0.save()
                    messages.add_message(request, messages.SUCCESS,
                        "Also updated %s for %s." % (STEP_DESC[field], c0.student.name()))
                    
            if hasattr(c, 'send_letter_now'):
                # send instructor's letter
                assert case.public_attachments_size() <= MAX_ATTACHMENTS # should be ensured by "review letter" step
                c.send_letter(_currentuser(request))
                messages.add_message(request, messages.INFO, "Letter sent to student summarizing case.")

            if hasattr(c, 'send_contact_mail'):
                # send initial contact email
                c.send_contact_email()
                messages.add_message(request, messages.INFO, "Email sent to student notifying of case.")
                for c0 in also_contact:
                    textkey = 'also-contact_email_text-' + str(c0.id)
                    if textkey in request.POST and request.POST[textkey]=="on":
                        # only send the email if text was updated too
                        c0.contacted = form.cleaned_data['contacted']
                        c0.contact_email_text = form.cleaned_data['contact_email_text']
                        c0.save()
                        messages.add_message(request, messages.SUCCESS,
                            "Also updated %s for %s." % (STEP_DESC['contacted'], c0.student.name()))
                        c0.send_contact_email()
                        messages.add_message(request, messages.INFO, "Also emailed %s." % (c0.student.name()))
                    else:
                        # if not, give an error message.
                        messages.add_message(request, messages.ERROR,
                            mark_safe('Email not sent to %s since their "Contact Email Text" was not updated. You can <a href="%s">edit their contact info</a> if you wish.'
                            % (c0.student.name(),
                                reverse('discipline.views.edit_case_info',
                                    kwargs={'field': 'contacted', 'course_slug': course_slug, 'case_slug': c0.slug}))))
            
            if isinstance(case, DisciplineCaseChair):
                return HttpResponseRedirect(reverse('discipline.views.show_chair', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))
            else:
                return HttpResponseRedirect(reverse('discipline.views.show', kwargs={'course_slug': course_slug, 'case_slug': case.slug}))
    else:
        form = FormClass(instance=case)
    
    templates = DisciplineTemplate.objects.filter(field__in=form.fields.keys())
    tempaltesJSON = json.dumps([t.JSON_data() for t in templates])
    groupmembersJSON = case.groupmembersJSON()
    hasRelAct = len(case.related_activities())>0
    
    context = {'course': course, 'case': case, 'form': form,
        'templatesJSON': mark_safe(tempaltesJSON), 'groupmembersJSON': mark_safe(groupmembersJSON), 'hasRelAct': hasRelAct}
    if field == 'letter_review':
        context['currentuser'] = _currentuser(request)
    return render_to_response("discipline/edit_"+field+".html", context, context_instance=RequestContext(request))

Example 22

Project: coursys
Source File: views.py
View license
@requires_course_by_slug
@transaction.atomic
def submit(request, course_slug):
    person = get_object_or_404(Person,userid=request.user.username)
    course = get_object_or_404(CourseOffering, slug = course_slug)
    member = Member.objects.exclude(role='DROP').get(person=person, offering=course)
    error_info=None
    name = request.POST.get('GroupName')
    if name:
        name = name[:30]
    #Check if group has a unique name
    if Group.objects.filter(name=name,courseoffering=course):
        error_info="A group named \"%s\" already exists" % (name)
        messages.add_message(request, messages.ERROR, error_info)
        return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
    #Check if the group name is empty, these two checks may need to be moved to forms later.
    if name == "":
        error_info = "Group name cannot be empty: please enter a group name."
        messages.add_message(request, messages.ERROR, error_info)
        return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
    

    else:
        # find selected activities
        selected_act = []
        activities = Activity.objects.filter(offering=course, group=True, deleted=False)
        if not is_course_staff_by_slug(request, course_slug):
            activities = activities.exclude(status='INVI')

        for activity in activities:
            activityForm = ActivityForm(request.POST, prefix=activity.slug)
            if activityForm.is_valid() and activityForm.cleaned_data['selected'] == True:
                selected_act.append(activity)
        
        # no selected activities: fail.
        if not selected_act:
            messages.add_message(request, messages.ERROR, "Group not created: no activities selected.")
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        
        #groupForSemesterForm = GroupForSemesterForm(request.POST)
        #if groupForSemesterForm.is_valid():
        #    groupForSemester = groupForSemesterForm.cleaned_data['selected']
        groupForSemester = False
        
        #validate database integrity before saving anything. 
        #If one student is in a group for an activity, he/she cannot be in another group for the same activity.
        if is_course_student_by_slug(request, course_slug):
            isStudentCreatedGroup = True
            studentList = []
            studentList.append(member)
        elif is_course_staff_by_slug(request, course_slug):
            isStudentCreatedGroup = False
            studentList = []
            students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
            for student in students:
                studentForm = StudentForm(request.POST, prefix = student.person.userid)
                if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
                    studentList.append(student)
        #Check if students has already in a group
        if _validateIntegrity(request,isStudentCreatedGroup, groupForSemester, course, studentList, selected_act) == False:
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        #No selected members,group creating will fail.        
        if not studentList:
            messages.add_message(request, messages.ERROR, "Group not created: no members selected.")
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))
        
        group = Group(name=name, manager=member, courseoffering=course, groupForSemester = groupForSemester)
        group.save()
        #LOG EVENT#
        l = LogEntry(userid=request.user.username,
        description="created a new group %s for %s." % (group.name, course),
        related_object=group )
        l.save()

        if is_course_student_by_slug(request, course_slug):
            for activity in selected_act:
                groupMember = GroupMember(group=group, student=member, confirmed=True, activity_id=activity.id)
                groupMember.save()
                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                description="automatically became a group member of %s for activity %s." % (group.name, groupMember.activity),
                    related_object=groupMember )
                l.save()

            messages.add_message(request, messages.SUCCESS, 'Group Created')
            return HttpResponseRedirect(reverse('groups.views.groupmanage', kwargs={'course_slug': course_slug}))

        elif is_course_staff_by_slug(request, course_slug):
            students = Member.objects.select_related('person').filter(offering = course, role = 'STUD')
            for student in students:
                studentForm = StudentForm(request.POST, prefix = student.person.userid)
                if studentForm.is_valid() and studentForm.cleaned_data['selected'] == True:
                    for activity in selected_act:
                        groupMember = GroupMember(group=group, student=student, confirmed=True, activity_id=activity.id)
                        groupMember.save()
                        #LOG EVENT#
                        l = LogEntry(userid=request.user.username,
                        description="added %s as a group member to %s for activity %s." % (student.person.userid,group.name, groupMember.activity),
                            related_object=groupMember )
                        l.save()
                    
                    n = NewsItem(user=student.person, author=member.person, course=group.courseoffering,
                     source_app="group", title="Added to Group",
                     content="You have been added the group %s." % (group.name),
                     url=reverse('groups.views.groupmanage', kwargs={'course_slug':course.slug})
                    )
                    n.save()
                    
            messages.add_message(request, messages.SUCCESS, 'Group Created')
            return HttpResponseRedirect(reverse('groups.views.view_group', kwargs={'course_slug': course_slug, 'group_slug': group.slug}))
        else:
            return HttpResponseForbidden()

Example 23

Project: Observatory
Source File: projects.py
View license
@login_required
def add(request):
  feed_repo_form = FeedRepositoryForm()
  cloned_repo_form = ClonedRepositoryForm()
  project_form = ProjectForm()
  blog_form = BlogForm()
  
  form_keys = {
    1: ('title', 'description', 'website', 'wiki'),
    2: ('web_url', 'clone_url', 'vcs', 'repo_rss', 'cmd'),
    3: ('url', 'rss')
  }
  
  if 'current' in request.POST:
    current = int(request.POST['current'])
  else:
    current = 0
  
  if current == 1:
    project_form = ProjectForm(request.POST)
    if not project_form.is_valid():
      current -= 1
  
  elif current == 2:
    if 'clone_url' in request.POST:
      cloned_repo_form = ClonedRepositoryForm(request.POST)
      if not cloned_repo_form.is_valid():
        current -= 1
    elif 'repo_rss' in request.POST:
      feed_repo_form = FeedRepositoryForm(request.POST)
      if not feed_repo_form.is_valid():
        current -= 1
  
  elif current == 3:
    blog_form = BlogForm(request.POST)
    if not ('url' not in request.POST or blog_form.is_valid()):
      current -= 1
  
  # go to the next form
  current += 1
  
  # if there are more parts to the form
  if current < 4:
    # remove the csrf token and current from a copy of the POST data
    post = request.POST.copy()
    if 'csrfmiddlewaretoken' in post:
      post.pop('csrfmiddlewaretoken')
      post.pop('current')

      # remove any of the keys that should be set on this form page
      for key in form_keys[current]:
        try:
          post.pop(key)
        except:
          pass
    
    return render_to_response('projects/add.html', {
        'parts': [1, 2, 3],
        'current': current,
        'previous_data': post,
        'cloned_repo_form': cloned_repo_form,
        'feed_repo_form': feed_repo_form,
        'project_form': project_form,
        'blog_form': blog_form,
        'js_page_id': 'add_project'
      }, context_instance = RequestContext(request))
  
  # otherwise, if the form is complete, create the project
  else:
    # validate and clean all forms
    project_form = ProjectForm(request.POST)
    cloned_repo_form = ClonedRepositoryForm(request.POST)
    feed_repo_form = FeedRepositoryForm(request.POST)
    blog_form = BlogForm(request.POST)
    
    for form in [project_form, cloned_repo_form, feed_repo_form, blog_form]:
      form.is_valid()
    
    # create the blog object
    if 'rss' in request.POST:
      blog = Blog(url = blog_form.cleaned_data['url'],
                  rss = blog_form.cleaned_data['rss'],
                  from_feed = True)
    else:
      blog = Blog(from_feed = False)
    blog.save()

    # create the repository object
    # if using google code removes read only addition
    # if [email protected] is mistakenly typed, git:// is placed in
    if 'clone_url' in request.POST:
      url = cloned_repo_form.cleaned_data['clone_url']
      gitfix = url.replace('[email protected]', 'git://')
      url = gitfix
      if "google.com" in url:
        split = url.split(' ')
        url = split[0]

      repo = Repository(web_url = cloned_repo_form.cleaned_data['web_url'],
                        clone_url = url,
                        from_feed = False)
    else:
      repo = Repository(web_url = feed_repo_form.cleaned_data['web_url'],
                        repo_rss = feed_repo_form.cleaned_data['repo_rss'],
                        from_feed = True)
    repo.save()

    # create the project object
    project = Project(title = project_form.cleaned_data['title'],
                      website = project_form.cleaned_data['website'],
                      wiki = project_form.cleaned_data['wiki'],
                      description = project_form.cleaned_data['description'],
                      active = True,
                      repository_id = repo.id,
                      blog_id = blog.id,
					  pending = True)

    # get the project a primary key
    project.save()

    # associate the current user with the project as an author
    project.authors.add(request.user)

    # save the project again
    project.save()

    # Set the active flag as true
    project.active = True

    # Save the project again
    project.save()

    # redirect to the show page for the new project
    return HttpResponseRedirect(reverse(show, args = (project.url_path,)))

Example 24

Project: coursys
Source File: views.py
View license
@retry_transaction()
@transaction.atomic
def _show_components_student(request, course_slug, activity_slug, userid=None, template="dashboard_student.html", staff=False):
    """
    Show all the component submission history of this activity
    """
    if userid == None:
        userid = request.user.username
    course = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(course.activity_set,slug=activity_slug, deleted=False)
    student = get_object_or_404(Person, find_userid_or_emplid(userid))
    cansubmit = True
    submission_configured = SubmissionComponent.objects.filter(activity_id=activity.id).exists()
    if not submission_configured:
        return NotFoundResponse(request)

    submission_info = SubmissionInfo(student=student, activity=activity)
    submission_info.get_most_recent_components()
    if activity.multisubmit():
        submission_info.get_all_components()

    any_submissions = bool(submission_info.submissions)

    if submission_info.submissions and activity.due_date and activity.due_date < submission_info.latest().created_at:
        late = submission_info.latest().created_at - activity.due_date
    else:
        late = 0
    
    if activity.group:
        gm = GroupMember.objects.filter(student__person=student, activity=activity, confirmed=True)
        if gm:
            group = gm[0].group
            member = gm[0].student
        else:
            group = None

    else:
        group = None

    # activity should be submitable
    cansubmit = cansubmit and activity.submitable()

    if not cansubmit:
        messages.add_message(request, messages.ERROR, "This activity is not submittable.")
        return render(request, "submission/" + template,
        {"course":course, "activity":activity, "submission_info": submission_info, 'any_submissions': any_submissions,
         "userid":userid, "late":late, "student":student, "group":group, "cansubmit":cansubmit})

    # get all components of activity
    component_list = select_all_components(activity)
    component_list.sort()
    component_form_list=[]

    if request.method == 'POST':
        component_form_list = make_form_from_list(component_list, request=request)
        submitted_comp = []    # list all components which has content submitted in the POST
        not_submitted_comp = [] #list allcomponents which has no content submitted in the POST
        if not activity.group:
            new_sub = StudentSubmission()   # the submission foreign key for newly submitted components
            new_sub.member = get_object_or_404(Member, offering__slug=course_slug, person__userid=request.user.username)
        elif gm:
            new_sub = GroupSubmission()
            new_sub.group = group
            new_sub.creator = member
        else:
            messages.add_message(request, messages.ERROR, "This is a group submission. You cannot submit since you aren't in a group.")
            return ForbiddenResponse(request)
        new_sub.activity = activity

        # begin validating uploaded data
        submitted_comp = []
        not_submitted_comp = []
        # validate forms one by one
        for data in component_form_list:
            component = data['comp']
            form = data['form']
            if form.is_valid():
                sub = form.save(commit=False)
                sub.component = component
                submitted_comp.append(sub)
            else:
                # hack to replace the "required" message to something more appropriate
                for k,v in form.errors.items():
                    for i,e in enumerate(v):
                        if e == "This field is required.":
                            v[i] = "Nothing submitted."

                not_submitted_comp.append(component)
        # check duplicate filenames here
        all_ok = False
        while not all_ok:
            all_ok = True
            d = {}
            if not activity.multisubmit():
                # single-submit logic: don't want to overrite filenames from earlier submissions that are still in-play
                for c,s in submission_info.components_and_submitted():
                    d[c] = s and s.get_filename()
            # filenames from this submission
            for s in submitted_comp:
                d[s.component] = s.get_filename()
            # a list holding all file names
            file_name_list = [a[1] for a in d.items() if a[1] is not None]
            to_be_removed = []
            for (i, s) in enumerate(submitted_comp):
                if file_name_list.count(s.get_filename()) > 1:
                    all_ok = False
                    to_be_removed.append(i)
                    not_submitted_comp.append(s.component)
                    #HACK: modify the 'errors' field in the form
                    for data in component_form_list:
                        if s.component == data['comp']:
                            # assume we have only one field for submission form
                            field_name = data['form'].fields.keys()[0]
                            data['form']._errors[field_name] = ErrorList([u"This file has the same name as another file in your submission."])
            # remove those has errors in submitted_comp
            to_be_removed.reverse()
            for t in to_be_removed:
                submitted_comp.pop(t)
        # all okay now
        # end validating, begin saving
        if len(submitted_comp) > 0:
            new_sub.save()    
        for sub in submitted_comp:
            sub.submission = new_sub
            sub.save()
            #LOG EVENT#
            if activity.group:
                group_str = " as a member of group %s" % new_sub.group.name
            else:
                group_str = ""
            l = LogEntry(userid=request.user.username,
                  description=u"submitted for %s %s%s" % (activity, sub.component.title, group_str),
                  related_object=sub)
            l.save()

        if len(not_submitted_comp) == 0:
            messages.add_message(request, messages.SUCCESS, "Your submission was successful.")
            return HttpResponseRedirect(reverse(show_components, args=[course_slug, activity_slug]))

        return render(request, "submission/submission_error.html",
            {"course":course, "activity":activity, "component_list":component_form_list,
            "submitted_comp":submitted_comp, "not_submitted_comp":not_submitted_comp})
    else: #not POST
        component_form_list = make_form_from_list(component_list)
        return render(request, "submission/" + template,
        {'component_form_list': component_form_list, "course": course, "activity": activity, "submission_info": submission_info,
         "userid":userid, "late":late, "student":student, "group":group,
         "cansubmit":cansubmit, "is_staff":staff, 'any_submissions': any_submissions})

Example 25

Project: virtmgr
Source File: views.py
View license
def index(request, host_id, vname):

   if not request.user.is_authenticated():
      return HttpResponseRedirect('/')

   kvm_host = Host.objects.get(user=request.user.id, id=host_id)

   def add_error(msg, type_err):
      error_msg = Log(host_id=host_id, 
                      type=type_err, 
                      message=msg, 
                      user_id=request.user.id
                      )
      error_msg.save()

   def get_vms():
      try:
         vname = {}
         for id in conn.listDomainsID():
            id = int(id)
            dom = conn.lookupByID(id)
            vname[dom.name()] = dom.info()[0]
         for id in conn.listDefinedDomains():
            dom = conn.lookupByName(id)
            vname[dom.name()] = dom.info()[0]
         return vname
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_storages():
      try:
         storages = []
         for name in conn.listStoragePools():
            storages.append(name)
         for name in conn.listDefinedStoragePools():
            storages.append(name)
         return storages
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def vm_conn():
      try:
         flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
         auth = [flags, creds, None]
         uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
         conn = libvirt.openAuth(uri, auth, 0)
         return conn
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_dom(vname):
      try:
         dom = conn.lookupByName(vname)
         return dom
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   if not kvm_host.login or not kvm_host.passwd:
      def creds(credentials, user_data):
         for credential in credentials:
            if credential[0] == libvirt.VIR_CRED_AUTHNAME:
               credential[4] = request.session['login_kvm']
               if len(credential[4]) == 0:
                  credential[4] = credential[3]
            elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
               credential[4] = request.session['passwd_kvm']
            else:
               return -1
         return 0
   else:
      def creds(credentials, user_data):
         for credential in credentials:
            if credential[0] == libvirt.VIR_CRED_AUTHNAME:
               credential[4] = kvm_host.login
               if len(credential[4]) == 0:
                  credential[4] = credential[3]
            elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
               credential[4] = kvm_host.passwd
            else:
               return -1
         return 0

   def get_vm_active():
      try:
         state = dom.isActive()
         return state
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_uuid():
      try:
         xml = dom.XMLDesc(0)
         uuid = util.get_xml_path(xml, "/domain/uuid")
         return uuid
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_xml():
      try:
         xml = dom.XMLDesc(0)
         xml_spl = xml.split('\n')
         return xml_spl
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_mem():
      try:
         xml = dom.XMLDesc(0)
         mem = util.get_xml_path(xml, "/domain/currentMemory")
         mem = int(mem) * 1024
         return mem
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_core():
      try:
         xml = dom.XMLDesc(0)
         cpu = util.get_xml_path(xml, "/domain/vcpu")
         return cpu
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_vnc():
      try:
         xml = dom.XMLDesc(0)
         vnc = util.get_xml_path(xml, "/domain/devices/graphics/@port")
         return vnc
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_hdd():
      try:
         xml = dom.XMLDesc(0)
         hdd_path = util.get_xml_path(xml, "/domain/devices/disk[1]/source/@file")
         hdd_fmt = util.get_xml_path(xml, "/domain/devices/disk[1]/driver/@type")
         #image = re.sub('\/.*\/', '', hdd_path)
         size = dom.blockInfo(hdd_path, 0)[0]
         #return image, size, hdd_fmt
         return hdd_path, size, hdd_fmt
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_cdrom():
      try:
         xml = dom.XMLDesc(0)
         cdr_path = util.get_xml_path(xml, "/domain/devices/disk[2]/source/@file")
         if cdr_path:
            #image = re.sub('\/.*\/', '', cdr_path)
            size = dom.blockInfo(cdr_path, 0)[0]
            #return image, cdr_path, size
            return cdr_path, cdr_path, size
         else:
            return cdr_path
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_boot_menu():
      try:
         xml = dom.XMLDesc(0)
         boot_menu = util.get_xml_path(xml, "/domain/os/bootmenu/@enable")
         return boot_menu
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"
   
   def get_vm_arch():
      try:
         xml = dom.XMLDesc(0)
         arch = util.get_xml_path(xml, "/domain/os/type/@arch")
         return arch
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_nic():
      try:
         xml = dom.XMLDesc(0)
         mac = util.get_xml_path(xml, "/domain/devices/interface/mac/@address")
         nic = util.get_xml_path(xml, "/domain/devices/interface/source/@network")
         if nic is None:
         	nic = util.get_xml_path(xml, "/domain/devices/interface/source/@bridge")
         return mac, nic
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"
      
   def mnt_iso_on(vol):
      try:
         for storage in storages:
            stg = conn.storagePoolLookupByName(storage)
            for img in stg.listVolumes():
               if vol == img:
                  vl = stg.storageVolLookupByName(vol)
         xml = """<disk type='file' device='cdrom'>
                     <driver name='qemu' type='raw'/>
                     <target dev='hdc' bus='ide'/>
                     <source file='%s'/>
                     <readonly/>
                  </disk>""" % vl.path()
         dom.attachDevice(xml)
         xmldom = dom.XMLDesc(0)
         conn.defineXML(xmldom)
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def mnt_iso_off(vol):
      try:
         for storage in storages:
            stg = conn.storagePoolLookupByName(storage)
            for img in stg.listVolumes():
               if vol == img:
                  vl = stg.storageVolLookupByName(vol)
         xml = dom.XMLDesc(0)
         iso = "<disk type='file' device='cdrom'>\n      <driver name='qemu' type='raw'/>\n      <source file='%s'/>" % vl.path()
         xmldom = xml.replace("<disk type='file' device='cdrom'>\n      <driver name='qemu' type='raw'/>", iso)
         conn.defineXML(xmldom)
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def umnt_iso_on():
      try:
         xml = """<disk type='file' device='cdrom'>
                     <driver name="qemu" type='raw'/>
                     <target dev='hdc' bus='ide'/>
                     <readonly/>
                  </disk>"""
         dom.attachDevice(xml)
         xmldom = dom.XMLDesc(0)
         conn.defineXML(xmldom)
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def umnt_iso_off():
      try:
         xml = dom.XMLDesc(0)
         cdrom = get_vm_cdrom()[1]
         xmldom = xml.replace("<source file='%s'/>\n" % cdrom,"")
         conn.defineXML(xmldom)
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def find_all_iso():
      try:
         iso = []
         for storage in storages:
            stg = conn.storagePoolLookupByName(storage)
            stg.refresh(0)
            for img in stg.listVolumes():
               if re.findall(".iso", img) or re.findall(".ISO", img):
                  iso.append(img)
         return iso
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"
   
   def get_vm_autostart():
      try:
         return dom.autostart()
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def page_refresh():
      try:
         return HttpResponseRedirect('/vm/' + host_id + '/' + vname + '/' )
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_vm_state():
      try:
         return dom.info()[0]
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def vm_cpu_usage():
      try:
         nbcore = conn.getInfo()[2]
         cpu_use_ago = dom.info()[4]
         time.sleep(1) 
         cpu_use_now = dom.info()[4]
         diff_usage = cpu_use_now - cpu_use_ago
         cpu_usage = 100 * diff_usage / (1 * nbcore * 10**9L)
         return cpu_usage
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_memusage():
      try:
         allmem = conn.getInfo()[1] * 1048576
         dom_mem = dom.info()[1] * 1024
         percent = (dom_mem * 100) / allmem
         return allmem, percent
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_all_core():
      try:
         allcore = conn.getInfo()[2]
         return allcore
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def vm_create_snapshot():
      try:
         xml = """<domainsnapshot>\n
                     <name>%d</name>\n
                     <state>shutoff</state>\n
                     <creationTime>%d</creationTime>\n""" % (time.time(), time.time())
         xml += dom.XMLDesc(0)
         xml += """<active>0</active>\n
                  </domainsnapshot>"""
         dom.snapshotCreateXML(xml, 0)
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   def get_snapshot_num():
      try:
         return dom.snapshotNum(0)
      except libvirt.libvirtError as e:
         add_error(e, 'libvirt')
         return "error"

   conn = vm_conn()
   errors = []

   if conn == None:
      return HttpResponseRedirect('/overview/' + host + '/')

   all_vm = get_vms()
   dom = get_dom(vname)
   active = get_vm_active()
   state = get_vm_state()
   uuid = get_vm_uuid()
   memory = get_vm_mem()
   core =  get_vm_core()
   autostart = get_vm_autostart()
   vnc_port = get_vm_vnc()
   hdd = get_vm_hdd()
   boot_menu = get_vm_boot_menu()
   vm_arch = get_vm_arch()
   vm_nic = get_vm_nic()
   cdrom = get_vm_cdrom()
   storages = get_storages()
   isos = find_all_iso()
   all_core = get_all_core()
   cpu_usage = vm_cpu_usage()
   mem_usage = get_memusage()
   num_snapshot = get_snapshot_num()
   vm_xml = get_vm_xml()

   # Post form html
   if request.method == 'POST':
      if request.POST.get('suspend',''):
         try:
            dom.suspend()
            msg = _('Suspend VM: ')
            msg = msg + vname
            add_error(msg, 'user')
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            msg = _('Error: VM alredy suspended')
            errors.append(msg)
      if request.POST.get('resume',''):
         try:
            dom.resume()
            msg = _('Resume VM: ')
            msg = msg + vname
            add_error(msg, 'user')
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            msg = _('Error: VM alredy resume')
            errors.append(msg)
      if request.POST.get('start',''):
         try:
            dom.create()
            msg = _('Start VM: ')
            msg = msg + vname
            add_error(msg, 'user')
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            msg = _('Error: VM alredy start')
            errors.append(msg)
      if request.POST.get('shutdown',''):
         try:
            dom.shutdown()
            msg = _('Shutdown VM: ')
            msg = msg + vname
            add_error(msg, 'user')
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            msg = _('Error: VM alredy shutdown')
            errors.append(msg)
      if request.POST.get('destroy',''):
         try:
            dom.destroy()
            msg = _('Force shutdown VM: ')
            msg = msg + vname
            add_error(msg, 'user')
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            msg = _('Error: VM alredy shutdown')
            errors.append(msg)
      if request.POST.get('snapshot',''):
         try:
            msg = _('Create snapshot for VM: ')
            msg = msg + vname
            add_error(msg, 'user')
            vm_create_snapshot()
            message = _('Successful create snapshot')
            return render_to_response('vm.html', locals())
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            msg = _('Error: create snapshot')
            errors.append(msg)
      if request.POST.get('auto_on',''):
         try:
            msg = _('Enable autostart for VM: ')
            msg = msg + vname
            add_error(msg, 'user')
            dom.setAutostart(1)
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            return "error"
      if request.POST.get('auto_off',''):
         try:
            msg = _('Disable autostart for VM: ')
            msg = msg + vname
            add_error(msg, 'user')
            dom.setAutostart(0)
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            return "error"
      if request.POST.get('disconnect',''):
         iso = request.POST.get('iso_img','')
         if state == 1:
            umnt_iso_on()
         else:
            umnt_iso_off()
      if request.POST.get('connect',''):
         iso = request.POST.get('iso_img','')     
         if state == 1:
            mnt_iso_on(iso)
         else:
            mnt_iso_off(iso)
      if request.POST.get('undefine',''):
         try:
            dom.undefine()
            msg = _('Undefine VM: ')
            msg = msg + vname
            add_error(msg, 'user')
            return HttpResponseRedirect('/overview/%s/' % (host_id))
         except libvirt.libvirtError as e:
            add_error(e, 'libvirt')
            return "error"
      if not errors:
         return HttpResponseRedirect('/vm/%s/%s/' % (host_id, vname))
      else:
         return render_to_response('vm.html', locals())

   conn.close()
   
   return render_to_response('vm.html', locals())

Example 26

Project: AutoO_with_django
Source File: views.py
View license
def admin(request, module="", action=""):
  def logRecord(r_action='', r_table='', r_data=''):
    record_name = request.session['user_name']
    record_time = time.strftime('%Y-%m-%d %H:%M',time.localtime())
    data_str = ''
    for temp in sorted(r_data):
      data_str += str(temp)+'='+r_data[temp]+' '
    log_op = Logrecord(user=record_name, time=record_time, action=r_action, table=r_table, data=data_str)
    log_op.save()
  
  if 'loginToken' in request.session and request.session['user_admin']:
    if module == 'project':
      if action != '':
        if action == "add" and request.session['user_sys']:
          proj_alias = request.POST['alias_name']
          proj_name = request.POST['name']
          proj_remark = request.POST['remark']
          obj = Project(alias=proj_alias, name=proj_name, remark=proj_remark)
          obj.save()
          logRecord(action, 'project', request.POST)
          result = {}
          result['code'] = 1
          result['message'] = "添加成功"
        elif action == "del":
          pid = request.POST['id']
          if request.session['user_sys'] or pid == request.session['user_proj']:
            Project.objects.get(id=pid).delete()
            logRecord(action, 'project', request.POST)
            result = {}
            result['code'] = 1
            result['message'] = "删除成功"
          else:
            result = {}
            result['code'] = 1
            result['message'] = "无权限删除"
        elif action.isdigit():
          return HttpResponse(action)
        else:         
          result = {}
          result['code'] = 0
          result['message'] = "操作失败"
        return HttpResponse(json.dumps(result), content_type="application/json")
      else:
        projects = Project.objects.all().order_by('alias')
        rsp = render(request, 'admin_project.html', locals())
        return HttpResponse(rsp)
    elif module == 'servers':
      if action != '':
        if action == "getinfo":
          if 'ipaddr' in request.POST and request.POST['ipaddr'] != "":
            ipaddr = request.POST['ipaddr']
            data_trans = request.POST['data_trans']
            snmpsession = netsnmp.Session(Version = 2, DestHost = ipaddr, Timeout=50000, ErrorStr='Cannot connect')
            oid_name = netsnmp.Varbind('.1.3.6.1.2.1.1.5.0')  #主机名oid
            bind_name = netsnmp.VarList(oid_name)

            oid_cpu = netsnmp.Varbind('.1.3.6.1.2.1.25.3.3.1.2')  #CPU负载oid
            bind_cpu = netsnmp.VarList(oid_cpu)

            oid_mem = netsnmp.Varbind('.1.3.6.1.2.1.25.2.2.0')  #内存总数oid
            bind_mem = netsnmp.VarList(oid_mem)

            oid_ip = netsnmp.Varbind('.1.3.6.1.2.1.4.20.1.1')  #IP地址oid
            bind_ip = netsnmp.VarList(oid_ip)

            snmp_name = snmpsession.get(bind_name)
            snmp_cpu = snmpsession.walk(bind_cpu)
            snmp_mem = snmpsession.get(bind_mem)
            snmp_ip = snmpsession.walk(bind_ip)

            result_name = snmp_name[0]

            i = 0
            for data in snmp_cpu:
              if data != '':
                i += 1

            result_cpu = i

            result_mem = int(snmp_mem[0])/1024
            if data_trans == "1":
              if result_mem <= 512:
                result_mem = 512
              else:
                result_mem = (result_mem/1024 + 1) * 1024

            result_ip = []
            i = 0
            for data in snmp_ip:
              if data != '127.0.0.1':
                oid = '.1.3.6.1.2.1.4.20.1.2.' + str(data)
                oid_ip_index = netsnmp.Varbind(oid)
                bind_ip_index = netsnmp.VarList(oid_ip_index)
                snmp_ip_index = snmpsession.get(bind_ip_index)
                ip_index = snmp_ip_index[0]
                oid_ip_name = netsnmp.Varbind('.1.3.6.1.2.1.2.2.1.2.' + str(ip_index))
                bind_ip_name = netsnmp.VarList(oid_ip_name)
                snmp_ip_name = snmpsession.get(bind_ip_name)
                ip_name = snmp_ip_name[0]
                result_ip.append(data)

            result = {}
            result['code'] = 0
            result['host'] = result_name
            result['cpu'] = result_cpu
            result['mem'] = result_mem
            result['ip'] = "|".join(result_ip)
            result['ip_disp'] = result['ip'].replace("|","\r\n")
            return HttpResponse(json.dumps(result), content_type="application/json")
          else:
            projects = Project.objects.all().order_by('alias')
            rsp = render(request, 'user_index.html', locals())
            return HttpResponse(rsp)
        elif action == "add":
          asset_pid = request.POST['pid']
          asset_ip = request.POST['ip']
          asset_hostname = request.POST['hostname']
          asset_cpu = request.POST['cpu']
          asset_mem = request.POST['mem']
          asset_disk = request.POST['disk']
          if request.POST['type'] == '1':
            asset_type = "物理机"
          elif request.POST['type'] == '2':
            asset_type = "虚拟机"
          else:
            asset_type = "其他" 
          asset_srv = request.POST['srv']
          asset_desc = request.POST['desc']
          pid = Project.objects.get(id=asset_pid)
          if request.session['user_sys'] or asset_pid == request.session['user_proj']:
            obj = Server(pid=pid,
                         ip=asset_ip,
                         hostname=asset_hostname,
                         cpu=asset_cpu,
                         mem=asset_mem,
                         disk=asset_disk,
                         type=asset_type,
                         srv=asset_srv,
                         desc=asset_desc,
                         status='1')
            obj.save()
            logRecord(action, 'asset', request.POST)
            result = {}
            result['code'] = 1
            result['message'] = "添加成功"
          else:
            result = {}
            result['code'] = 0
            result['message'] = "未授权的操作"
        elif action == "del":
          id = request.POST['id']
          del_data = Server.objects.filter(id=id)
          del_id = str(del_data[0].pid.id)
          if request.session['user_sys'] or del_id == request.session['user_proj']:
            try:
              Server.objects.get(id=id).delete()
              logRecord(action, 'asset', request.POST)
              result = {}
              result['code'] = 1
              result['message'] = "删除成功"
            except:
              result = {}
              result['code'] = 0
              result['message'] = "删除异常"
          else:
              result = {}
              result['code'] = 0
              result['message'] = "未授权的操作"
        elif action.isdigit():
          if 'update' in request.GET:
            asset_pid = request.POST['pid']
            asset_ip = request.POST['ip']
            asset_hostname = request.POST['hostname']
            asset_cpu = request.POST['cpu']
            asset_mem = request.POST['mem']
            asset_disk = request.POST['disk']
            if request.POST['type'] == '1':
              asset_type = "物理机"
            elif request.POST['type'] == '2':
              asset_type = "虚拟机"
            else:
              asset_type = "其他" 
            asset_srv = request.POST['srv']
            asset_desc = request.POST['desc']
            asset_status = request.POST['status']
            asset_cacti = request.POST['cacti']
            asset_nagios = request.POST['nagios']
            if request.session['user_sys'] or asset_pid == request.session['user_proj']:
              try:
                Server.objects.filter(id=action).update(ip=asset_ip,
                  hostname=asset_hostname,
                  cpu=asset_cpu,
                  mem=asset_mem,
                  disk=asset_disk,
                  type=asset_type,
                  srv=asset_srv,
                  desc=asset_desc,
                  status = asset_status,
                  cacti = asset_cacti,
                  nagios = asset_nagios
                )
                logRecord('update', 'asset', request.POST)
                result = {}
                result['code'] = 1
                result['message'] = "资产修改成功"
              except:
                result = {}
                result['code'] = 0
                result['message'] = "资产修改未提交"
            else:
                result = {}
                result['code'] = 0
                result['message'] = "未授权的操作"
            return HttpResponse(json.dumps(result), content_type="application/json")
          else:
            try:
              queryset = Server.objects.select_related().get(id=action)
            except:
              return HttpResponse('无效ID')
            rsp = render(request, 'admin_display_server.html', locals())
            return HttpResponse(rsp)
        else:
          result = {}
          result['code'] = 0
          result['message'] = "操作失败"
        return HttpResponse(json.dumps(result), content_type="application/json")
      else:
        if 'page' in request.GET and request.GET['page'].isdigit():
          page_get = int(float(request.GET['page']))
        else:
          page_get = 1
        if 'query' in request.GET:
          if request.session['query'].has_key('op'):
            request.session['query'] = {'op':'True'}
            if 'pid' in request.POST:
              if request.POST['pid'] == "":
                try:
                  request.session['query_data'].pop('pid')
                except:
                  a = 1
              else:
                request.session['query_data']['pid'] = request.POST['pid']
            if 'ip' in request.POST:
              if request.POST['ip'] == "":
                try:
                  request.session['query_data'].pop('ip__contains')
                except:
                  a = 1
              else:
                request.session['query_data']['ip__contains'] = request.POST['ip']
            if 'srv' in request.POST:
              if request.POST['srv'] == "":
                try:
                  request.session['query_data'].pop('srv')
                except:
                  a = 1
              else:
                request.session['query_data']['srv'] = request.POST['srv']
            if 'status' in request.POST:
              if request.POST['status'] == "":
                try:
                  request.session['query_data'].pop('status')
                except:
                  a = 1
              else:
                request.session['query_data']['status'] = request.POST['status']
            exper = request.session['query_data']
          else:
            request.session['query'] = {'op':'true'}          
            if 'pid' in request.POST and request.POST['pid'] != "":
              request.session['query_data']['pid'] = request.POST['pid']
            if 'ip' in request.POST and request.POST['ip'] != "":
              request.session['query_data']['ip__contains'] = request.POST['ip']
            if 'srv' in request.POST and request.POST['srv'] != "":
              request.session['query_data']['srv'] = request.POST['srv']
            if 'status' in request.POST and request.POST['status'] != "":
              request.session['query_data']['status'] = request.POST['status']
            exper = request.session['query_data']
          
          servers = Server.objects.filter(**exper)
        else:
          request.session['query'] = {}
          request.session['query_data'] = {}
          if request.session['user_sys']:
            servers = Server.objects.select_related().all()
          else:
            servers = Server.objects.select_related().filter(pid=request.session['user_proj'])
        pagin = Paginator(servers,20)
        page_max = pagin.num_pages
        if page_get > page_max:
          page = page_max
        else:
          page = page_get
        data_list = pagin.page(page)
        if 'query' in request.GET:
          url_fp = "?query&page=1"
          if page <= 1:
            url_pp = "?query&page=1"
          else:
            url_pp = "?query&page=" + str((page - 1))
          if page >= page_max:
            url_np = "?query&page=" + str(page_max)
          else:
            url_np = "?query&page=" + str((page + 1))
          url_lp = "?query&page=" + str(page_max)
        else:
          url_fp = "?page=1"
          if page <= 1:
            url_pp = "?page=1"
          else:
            url_pp = "?page=" + str((page - 1))
          if page >= page_max:
            url_np = "?page=" + str(page_max)
          else:
            url_np = "?page=" + str((page + 1))
          url_lp = "?page=" + str(page_max)
        if request.session['user_sys']:
          projects = Project.objects.all().order_by('alias')
        else:
          projects = Project.objects.filter(id=request.session['user_proj']).order_by('alias')
        rsp = render(request, 'admin_servers.html', locals())
        return HttpResponse(rsp)
    else:
      rsp = render(request, 'admin_base.html', locals())
      return HttpResponse(rsp)
  else:
    return HttpResponseRedirect('/')

Example 27

Project: mybitbank
Source File: views.py
View license
@login_required
def send(request, selected_provider_id):
    '''
    handler for the transfers
    '''
    post_errors = []
    selected_provider_id = int(selected_provider_id)
    
    # set the request in the connector object
    connector.request = request
    
    if request.method == 'POST': 
        # we have a POST request
        form = forms.SendCurrencyForm(request.POST)
        
        if form.is_valid():
            # all validation rules pass
            from_account_identifier = form.cleaned_data['from_account']
            to_address = form.cleaned_data['to_address']
            to_account = form.cleaned_data['to_account']
            comment = form.cleaned_data['comment']
            comment_to = form.cleaned_data['comment_to']
            amount = form.cleaned_data['amount']
            provider_id = form.cleaned_data['provider_id']
            passphrase = form.cleaned_data['passphrase']
            
            # main exit flags
            move_exit = False
            sendfrom_exit = False
            
            # get from account details
            wallet = getWalletByProviderId(connector, selected_provider_id)
            list_of_accounts = wallet.listAccounts(gethidden=True, getarchived=True)
            from_account = None
            for account in list_of_accounts:
                if account['identifier'] == from_account_identifier:
                    from_account = account
                    break
            else:
                # account name not found, display error
                post_errors.append({'message': "The source account was not found!"})
                context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors)
                return render(request, 'transfer/index.html', context)
            
            # get to account details if there is one
            to_account = wallet.getAccountByAddress(to_address)
            # if to_account is set then it is a local move, do a move()
            if to_account:
                # this address/account is hosted locally, do a move
                move_exit = connector.moveAmount(
                                                 from_account=from_account['name'],
                                                 to_account=to_account['name'],
                                                 provider_id=provider_id,
                                                 amount=amount,
                                                 comment=comment
                                                )
                
                # if there are errors, show them in the UI
                if move_exit is not True:
                    post_errors.append({'message': move_exit['message']})
                    context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors)
                    return render(request, 'transfer/index.html', context)
                
            else:
                # otherwise do a sendfrom(), it is a regular transaction
                if passphrase:
                    # a passphrase was given, unlock wallet first
                    unlock_exit = connector.walletPassphrase(passphrase, provider_id)
                    
                    if unlock_exit is not True:
                        # show form with error
                        post_errors.append({'message': unlock_exit['message']})
                        context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors, show_passphrase=True)
                        return render(request, 'transfer/index.html', context)
                
                # to_address not local, do a send
                sendfrom_exit = connector.sendFrom(
                                                   from_account=from_account['name'],
                                                   to_address=to_address,
                                                   amount=amount,
                                                   provider_id=provider_id,
                                                   comment=comment,
                                                   comment_to=comment_to
                                                  )
                
                # if there are errors, show them in the UI
                if type(sendfrom_exit) is dict and sendfrom_exit['code'] < 0:
                    
                    # check if passphrase is needed
                    if sendfrom_exit['code'] == -13:
                        # passphrase is needed
                        show_passphrase = True
                    else:
                        show_passphrase = False
                    
                    if not request.is_secure() and show_passphrase:
                        show_warning_ssl = 1
                    elif request.is_secure() and show_passphrase:
                        show_warning_ssl = -1
                    else:
                        show_warning_ssl = 0
                    
                    # show form with error
                    post_errors.append({'message': sendfrom_exit['message']})
                    context = commonContext(request=request, selected_provider_id=provider_id, form=form, errors=post_errors, show_passphrase=show_passphrase, show_warning_ssl=show_warning_ssl)
                    return render(request, 'transfer/index.html', context)
                
            if passphrase:
                # lock wallet again
                connector.walletLock(provider_id)
                
            # process the data in form.cleaned_data
            if move_exit:
                messages.success(request, 'Local move of %s %s completed from account "%s" to "%s"' % (amount, connector.config[provider_id]['currency'].upper(), from_account['name'], to_account['name']), extra_tags="success")
                events.addEvent(request, 'Local move occurred from "%s" to "%s" in the amount of %s %s' % (from_account['name'], to_account['name'], amount, connector.config[provider_id]['currency'].upper()), 'info')
                return HttpResponseRedirect(reverse('transactions:index', kwargs={'selected_provider_id': selected_provider_id, 'page': '1'}))  # Redirect after POST
            elif sendfrom_exit:
                messages.success(request, 'Transfer of %s %s initialized with transaction id %s' % (amount, connector.config[provider_id]['currency'].upper(), sendfrom_exit), extra_tags="success")
                events.addEvent(request, 'Transfer initialized from "%s" to "%s" of %s %s' % (from_account['name'], to_address, amount, connector.config[provider_id]['currency'].upper()), 'info')
                return HttpResponseRedirect(reverse('transactions:details', kwargs={'provider_id': provider_id, 'txid':sendfrom_exit}))  # Redirect after POST
        
        else:
            # form not valid
            #messages.error(request, 'There were some errors processing this form!', extra_tags="error")
            print "Error processing form!"
            
    else:
        # request not a POST
        form = forms.SendCurrencyForm()
        
    context = commonContext(request=request, selected_provider_id=selected_provider_id, form=form)
    
    return render(request, 'transfer/index.html', context)

Example 28

Project: classic.rhizome.org
Source File: views.py
View license
@login_required  
def edit(request, type, id):
    context = RequestContext(request)
    username = request.user.get_profile()       
        
    #CHECK THE TYPE, GRAB OBJECT OR CATCH MISSING INFO
    if type == 'opportunities':
        announcement = get_object_or_404(Opportunity, id=id, is_spam=False)
        announcement_form = OpportunityForm(
                                request.POST or None, 
                                request.FILES or None, 
                                instance=announcement, 
                                initial={'username':username}
                            )
    elif type == 'jobs':
        announcement = get_object_or_404(Job, id=id, is_spam=False)
        announcement_form = JobForm(
                                request.POST or None, 
                                request.FILES or None, 
                                instance=announcement,  
                                initial={'username':username}
                                )
    elif type == 'events':
        announcement = get_object_or_404(Event, id=id, is_spam=False)
        announcement_form = EventForm(
                                request.POST or None, 
                                request.FILES or None, 
                                instance=announcement, 
                                initial={'username':username}
                            )
    else:
        raise Http404
    
    if not announcement.can_edit():
        # can only edit if announcement less than 2 wks old...    
        return HttpResponseRedirect(reverse('announce_index'))  
    else:
        # MAKE SURE THE USER OWNS THE ANNOUNCEMENT
        if request.user != announcement.user:
            return HttpResponseRedirect(reverse('announce_index'))  
        else:
            # HANDLE THE POST
            if request.method == 'POST':
            
                if request.POST.get("form-type") == "opportunity-form":
                    announcement_form = OpportunityForm(
                                            request.POST, 
                                            request.FILES or None, 
                                            instance=announcement, 
                                            initial={'username':username}
                                        )
                if request.POST.get("form-type") == "job-form":
                    announcement_form = JobForm(
                                            request.POST, 
                                            request.FILES or None, 
                                            instance=announcement, 
                                            initial={'username':username}
                                        )
                if request.POST.get("form-type") == "event-form":  
                    announcement_form = EventForm(
                                            request.POST, 
                                            request.FILES or None, 
                                            instance=announcement, 
                                            initial={'username':username}
                                            )
           
                if announcement_form.is_valid():
                    announcement = announcement_form.save(commit=False)
                    announcement.user_id = request.user.id
                    announcement.ip_address = request.META["REMOTE_ADDR"]
                    
                    if request.POST.get("delete_image"):
                        if announcement.image:
                            import os
                            if os.path.exists(announcement.image.path):
                                os.remove(announcement.image.path)
                        announcement.image = None
                    
                    #save now so can create thumbanail with id in title
                    announcement.save() 
                    
                    if announcement.image and not announcement.thumbnail:
                        announcement.thumbnail = create_thumbnail(announcement.image)
                        announcement.save()           
                    
                    ####
                    # if announcement is not yet published
                    ####
                    if request.POST.get("status") == "preview":
                        announcement.status = False
                        announcement.save()
                        return HttpResponseRedirect(reverse(preview, kwargs={'type':type, 'id':announcement.id}))                    
                        
                    if request.POST.get("status") == "publish":

                        if type == 'jobs' and not announcement.is_paid() and not request.user.get_profile().is_member():
                            return HttpResponseRedirect(reverse(job_payment))

                        if not moderator.process(announcement, request):
                            announcement.status = True
                            announcement.save()
                            send_to_announce_mailing_list(announcement.__class__, announcement, created=True)
 
                        return HttpResponseRedirect(reverse(thanks, kwargs={'type':type,'id':announcement.id}))

                    
                    ####
                    # if announcement is published
                    ####
                    if request.POST.get("status") == "unpublish":
                        announcement.status = False
                        announcement.save()
                        #return HttpResponseRedirect('/announce/%s/%s/preview/' % (type, announcement.id))
                        return HttpResponseRedirect(reverse(edit,kwargs={'type':type,'id':announcement.id}))

                    if request.POST.get("status") == "update":
                        moderator.process(announcement, request)
                            
                        #return HttpResponseRedirect('/announce/%s/%s/preview/' % (type, announcement.id))
                        return HttpResponseRedirect(reverse(thanks,kwargs={'type':type,'id':announcement.id}))
                
                    else:
                        if type == 'opportunities':   
                            announcement_form = OpportunityForm(request.POST)
                        if type == 'jobs':   
                            announcement_form = JobForm(request.POST)
                        if type == 'events':   
                            announcement_form = EventForm(request.POST)       
        
        return render_to_response(
            "announce/submit.html",
            {"announcement_form":announcement_form,
            "type": type  
            }, 
            context
            )

Example 29

Project: djangobb
Source File: views.py
View license
@transaction.atomic
def show_topic(request, topic_id, full=True):
    """
    * Display a topic
    * save a reply
    * save a poll vote

    TODO: Add reply in lofi mode
    """
    post_request = request.method == "POST"
    user_is_authenticated = request.user.is_authenticated()
    if post_request and not user_is_authenticated:
        # Info: only user that are logged in should get forms in the page.
        raise PermissionDenied

    topic = get_object_or_404(Topic.objects.select_related(), pk=topic_id)
    if not topic.forum.category.has_access(request.user):
        raise PermissionDenied
    Topic.objects.filter(pk=topic.id).update(views=F('views') + 1)

    last_post = topic.last_post

    if request.user.is_authenticated():
        topic.update_read(request.user)
    posts = topic.posts.all().select_related()

    moderator = request.user.is_superuser or request.user in topic.forum.moderators.all()
    if user_is_authenticated and request.user in topic.subscribers.all():
        subscribed = True
    else:
        subscribed = False

    # reply form
    reply_form = None
    form_url = None
    back_url = None
    if user_is_authenticated and not topic.closed:
        form_url = request.path + "#reply" # if form validation failed: browser should scroll down to reply form ;)
        back_url = request.path
        ip = request.META.get('REMOTE_ADDR', None)
        post_form_kwargs = {"topic":topic, "user":request.user, "ip":ip}
        if post_request and AddPostForm.FORM_NAME in request.POST:
            reply_form = AddPostForm(request.POST, request.FILES, **post_form_kwargs)
            if reply_form.is_valid():
                post = reply_form.save()
                messages.success(request, _("Your reply saved."))
                return HttpResponseRedirect(post.get_absolute_url())
        else:
            reply_form = AddPostForm(
                initial={
                    'markup': request.user.forum_profile.markup,
                    'subscribe': request.user.forum_profile.auto_subscribe,
                },
                **post_form_kwargs
            )

    # handle poll, if exists
    poll_form = None
    polls = topic.poll_set.all()
    if not polls:
        poll = None
    else:
        poll = polls[0]
        if user_is_authenticated: # Only logged in users can vote
            poll.deactivate_if_expired()
            has_voted = request.user in poll.users.all()
            if not post_request or not VotePollForm.FORM_NAME in request.POST:
                # It's not a POST request or: The reply form was send and not a poll vote
                if poll.active and not has_voted:
                    poll_form = VotePollForm(poll)
            else:
                if not poll.active:
                    messages.error(request, _("This poll is not active!"))
                    return HttpResponseRedirect(topic.get_absolute_url())
                elif has_voted:
                    messages.error(request, _("You have already vote to this poll in the past!"))
                    return HttpResponseRedirect(topic.get_absolute_url())

                poll_form = VotePollForm(poll, request.POST)
                if poll_form.is_valid():
                    ids = poll_form.cleaned_data["choice"]
                    queryset = poll.choices.filter(id__in=ids)
                    queryset.update(votes=F('votes') + 1)
                    poll.users.add(request.user) # save that this user has vote
                    messages.success(request, _("Your votes are saved."))
                    return HttpResponseRedirect(topic.get_absolute_url())

    highlight_word = request.GET.get('hl', '')
    view_data = {
        'categories': Category.objects.all(),
        'topic': topic,
        'posts_page': get_page(posts, request, forum_settings.TOPIC_PAGE_SIZE),
        'poll': poll,
        'poll_form': poll_form,
    }
    if full:
        view_data.update({
            'last_post': last_post,
            'form_url': form_url,
            'reply_form': reply_form,
            'back_url': back_url,
            'moderator': moderator,
            'subscribed': subscribed,
            'highlight_word': highlight_word,
        })
        return render(request, 'djangobb_forum/topic.html', view_data)
    else:
        return render(request, 'djangobb_forum/lofi/topic.html', view_data)

Example 30

Project: Observatory
Source File: views.py
View license
@login_required
def view_list(request,list_id=0,list_slug=None,view_completed=0):
    
    """
    Display and manage items in a task list
    """
    
    # Make sure the accessing user has permission to view this list.
    # Always authorize the "mine" view. Admins can view/edit all lists.

    if list_slug == "mine"  or list_slug == "recent-add" or list_slug == "recent-complete" :
        auth_ok =1
    else: 
        list = get_object_or_404(List, slug=list_slug)
        listid = list.id    
        
        # Check whether current user is a member of the group this list belongs to.
        if list.group in request.user.groups.all() or request.user.mentor or list_slug == "mine" :
            auth_ok = 1   # User is authorized for this view
        else: # User does not belong to the group this list is attached to
            messages.error(request, "You do not have permission to view/edit this list.")                                    

        
    # First check for items in the mark_done POST array. If present, change
    # their status to complete.
    if request.POST.getlist('mark_done'):
        done_items = request.POST.getlist('mark_done')
        # Iterate through array of done items and update its representation in the model
        for thisitem in done_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 1
            p.completed_date = datetime.datetime.now()
            p.save()
            messages.success(request, "Item \"%s\" marked complete." % p.title)                                             


    # Undo: Set completed items back to incomplete
    if request.POST.getlist('undo_completed_task'):
        undone_items = request.POST.getlist('undo_completed_task')
        for thisitem in undone_items:
            p = Item.objects.get(id=thisitem)
            p.completed = 0
            p.save()
            messages.success(request, "Previously completed task \"%s\" marked incomplete." % p.title)


    # And delete any requested items
    if request.POST.getlist('del_task'):
        deleted_items = request.POST.getlist('del_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            p.delete()
            messages.success(request, "Item \"%s\" deleted." % p.title)         

    # And delete any *already completed* items
    if request.POST.getlist('del_completed_task'):
        deleted_items = request.POST.getlist('del_completed_task')
        for thisitem in deleted_items:
            p = Item.objects.get(id=thisitem)
            p.delete()
            messages.success(request, "Deleted previously completed item \"%s\"."  % p.title)                       


    thedate = datetime.datetime.now()
    created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day)


    # Get list of items with this list ID, or filter on items assigned to me, or recently added/completed
    if list_slug == "mine":
        task_list = Item.objects.filter(assigned_to=request.user, completed=0)
        completed_list = Item.objects.filter(assigned_to=request.user, completed=1)
        
    elif list_slug == "recent-add":
        # We'll assume this only includes uncompleted items to avoid confusion.
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=(request.user.groups.all()),completed=0).order_by('-created_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)   
        
    elif list_slug == "recent-complete":
        # Only show items in lists that are in groups that the current user is also in.
        task_list = Item.objects.filter(list__group__in=request.user.groups.all(),completed=1).order_by('-completed_date')[:50]
        # completed_list = Item.objects.filter(assigned_to=request.user, completed=1)             


    else:
        task_list = Item.objects.filter(list=list.id, completed=0)
        completed_list = Item.objects.filter(list=list.id, completed=1)


    if request.POST.getlist('add_task') :
        form = AddItemForm(list, request.POST,initial={
        'assigned_to':request.user.id,
        'priority':999,
        })
        
        if form.is_valid():
            # Save task first so we have a db object to play with
            new_task = form.save()

            # Send email alert only if the Notify checkbox is checked AND the assignee is not the same as the submittor
            # Email subect and body format are handled by templates
            if "notify" in request.POST :
                if new_task.assigned_to != request.user :
                                        
                    # Send email
                    email_subject = render_to_string("todo/email/assigned_subject.txt", { 'task': new_task })                    
                    email_body = render_to_string("todo/email/assigned_body.txt", { 'task': new_task, 'site': current_site, })
                    try:
                        send_mail(email_subject, email_body, new_task.created_by.email, [new_task.assigned_to.email], fail_silently=False)
                    except:
                        messages.error(request, "Task saved but mail not sent. Contact your administrator.")
                        

            messages.success(request, "New task \"%s\" has been added." % new_task.title)                       
            
            return HttpResponseRedirect(request.path)

    else:
        if list_slug != "mine" and list_slug != "recent-add" and list_slug != "recent-complete" : # We don't allow adding a task on the "mine" view
            form = AddItemForm(list, initial={
                'assigned_to':request.user.id,
                'priority':999,
                } )

    if request.user.mentor :
        can_del = 1

    return render_to_response('todo/view_list.html', locals(), context_instance=RequestContext(request))

Example 31

Project: filebrowser-safe
Source File: views.py
View license
@xframe_options_sameorigin
def browse(request):
    """
    Browse Files/Directories.
    """

    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get('dir', ''))
    directory = get_path('')

    if path is None:
        msg = _('The requested Folder does not exist.')
        messages.add_message(request, messages.ERROR, msg)
        if directory is None:
            # The directory returned by get_directory() does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured(_("Error finding Upload-Folder. Maybe it does not exist?"))
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)
    abs_path = os.path.join(get_directory(), path)

    # INITIAL VARIABLES
    results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0}
    counter = {}
    for k, v in EXTENSIONS.items():
        counter[k] = 0

    dir_list, file_list = default_storage.listdir(abs_path)
    files = []
    for file in dir_list + file_list:

        # EXCLUDE FILES MATCHING ANY OF THE EXCLUDE PATTERNS
        filtered = not file or file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1

        # CREATE FILEOBJECT
        url_path = "/".join([s.strip("/") for s in
                            [get_directory(), path, file] if s.strip("/")])
        fileobject = FileObject(url_path)

        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and get_filterdate(request.GET.get('filter_date', ''), fileobject.date):
            append = True
        if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()):
            append = False

        # APPEND FILE_LIST
        if append:
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == 'Image':
                    results_var['images_total'] += 1
                if fileobject.filetype != 'Folder':
                    results_var['delete_total'] += 1
                elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                    results_var['delete_total'] += 1
                if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]:
                    results_var['select_total'] += 1
                elif not query.get('type'):
                    results_var['select_total'] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var['results_current'] += 1

        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1

    # SORTING
    query['o'] = request.GET.get('o', DEFAULT_SORTING_BY)
    query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER)
    defaultValue = ''
    if query['o'] in ['date', 'filesize']:
        defaultValue = 0.0
    files = sorted(files, key=lambda f: getattr(f, query['o']) or defaultValue)
    if not request.GET.get('ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get('ot') == "desc":
        files.reverse()

    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get('p', '1')
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render(request, 'filebrowser/index.html', {
        'dir': path,
        'p': p,
        'page': page,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'Media Library'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': ""
    })

Example 32

Project: django-facebookconnect
Source File: views.py
View license
def setup(request,redirect_url=None,
          registration_form_class=FacebookUserCreationForm,
          template_name='facebook/setup.html',
          extra_context=None):
    """
    setup
    ===============================
    
    Handles a new facebook user. There are three ways to setup a new facebook user.
     1. Link the facebook account with an existing django account.
     2. Create a dummy django account to attach to facebook. The user must always use
        facebook to login.
     3. Ask the user to create a new django account
     
    The built in template presents the user with all three options. Once setup is 
    complete the user will get redirected. The url used in the following order of 
    presidence:

      1. whatever url is in the 'next' get parameter passed to the setup url
      2. whatever url is passed to the setup view when the url is defined
      3. whatever url is defined in the LOGIN_REDIRECT_URL setting directive
    
    If you define a url to use this view, you can pass the following parameters:
     * redirect_url: Defines where to send the user after they are setup. This
                     can get overridden by the url in the 'next' get param passed on 
                     the url.
     * registration_form_class: Django form class to use for new user way #3 explained
                                above. The form should create a new user.
     * template_name: Template to use. Uses 'facebook/setup.html' by default.
     * extra_context: A context object whose contents will be passed to the template.
    """
    log.debug('in setup view')
    #you need to be logged into facebook.
    if not request.facebook.uid:
        log.debug('Need to be logged into facebook')
        url = reverse(facebook_login)
        if request.REQUEST.get(REDIRECT_FIELD_NAME,False):
            url += "?%s=%s" % (REDIRECT_FIELD_NAME, request.REQUEST[REDIRECT_FIELD_NAME])
        return HttpResponseRedirect(url)

    #setup forms
    login_form = AuthenticationForm()
    registration_form = registration_form_class()

    #figure out where to go after setup
    if request.REQUEST.get(REDIRECT_FIELD_NAME,False):
        redirect_url = request.REQUEST[REDIRECT_FIELD_NAME]
    elif redirect_url is None:
        redirect_url = getattr(settings, "LOGIN_REDIRECT_URL", "/")

    #check that this fb user is not already in the system
    try:
        FacebookProfile.objects.get(facebook_id=request.facebook.uid)
        # already setup, move along please
        return HttpResponseRedirect(redirect_url)
    except FacebookProfile.DoesNotExist, e:
        # not in the db, ok to continue
        pass

    #user submitted a form - which one?
    if request.method == "POST":
        log.debug('Submitted form')
        #lets setup a facebook only account. The user will have to use
        #facebook to login.
        if request.POST.get('facebook_only',False):
            log.debug('Facebook Only')
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            user = User(username=request.facebook.uid,
                        email=profile.email)
            user.set_unusable_password()
            user.save()
            profile.user = user
            profile.save()
            log.info("Added user and profile for %s!" % request.facebook.uid)
            user = authenticate(request=request)
            login(request, user)
            return HttpResponseRedirect(redirect_url)
        
        # user setup his/her own local account in addition to their facebook
        # account. The user will have to login with facebook unless they 
        # reset their password.
        elif request.POST.get('register',False):
            log.debug('Register a new account')
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            if profile.first_name != "(Private)":
                fname = profile.first_name
            if profile.last_name != "(Private)":
                lname = profile.last_name
            user = User(first_name=fname, last_name=lname)
            registration_form = registration_form_class(
                                        data=request.POST, instance=user)
            if registration_form.is_valid():
                user = registration_form.save()
                profile.user = user
                profile.save()
                log.info("Added user and profile for %s!" % request.facebook.uid)
                login(request, authenticate(request=request))
                return HttpResponseRedirect(redirect_url)
            else:
                request.user = User()
                request.user.facebook_profile = FacebookProfile(facebook_id=request.facebook.uid)
    
        #user logs in in with an existing account, and the two are linked.
        elif request.POST.get('login',False):
            login_form = AuthenticationForm(data=request.POST)

            if login_form.is_valid():
                user = login_form.get_user()
                log.debug("Trying to setup FB: %s, %s" % (user,request.facebook.uid))
                if user and user.is_active:
                    FacebookProfile.objects.get_or_create(user=user, facebook_id=request.facebook.uid)
                    log.info("Attached facebook profile %s to user %s!" % (request.facebook.uid, user))
                    login(request, user)
                    return HttpResponseRedirect(redirect_url)
            else:
                request.user = User()
                request.user.facebook_profile = FacebookProfile(facebook_id=request.facebook.uid)
    
    #user didn't submit a form, but is logged in already. We'll just link up their facebook
    #account automatically.
    elif request.user.is_authenticated():
        log.debug('Already logged in')
        try:
            request.user.facebook_profile
        except FacebookProfile.DoesNotExist:
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            profile.user = request.user
            profile.save()
            log.info("Attached facebook profile %s to user %s!" % (profile.facebook_id,profile.user))

        return HttpResponseRedirect(redirect_url)
    
    # user just showed up
    else:
        log.debug('Setting up form...')
        request.user.facebook_profile = profile = FacebookProfile(facebook_id=request.facebook.uid)
        login_form = AuthenticationForm(request)
        log.debug('creating a dummy user')
        fname = lname = ''
        if profile.first_name != "(Private)":
            fname = profile.first_name
        if profile.last_name != "(Private)":
            lname = profile.last_name
        user = User(first_name=fname, last_name=lname)
        registration_form = registration_form_class(instance=user)
    
    log.debug('going all the way...')
    
    # add the extra_context to this one
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    template_dict = {
        "login_form":login_form,
        "registration_form":registration_form
    }
    
    # we only need to set next if its been passed in the querystring or post vars
    if request.REQUEST.get(REDIRECT_FIELD_NAME, False):
        template_dict.update( {REDIRECT_FIELD_NAME: request.REQUEST[REDIRECT_FIELD_NAME]})
        
    return render_to_response(
        template_name,
        template_dict,
        context_instance=context)

Example 33

Project: syndicate
Source File: views.py
View license
@authenticate
def create(request):
    '''
    View for creating UG's
    '''
    session = request.session
    username = session['login_email']
    user = db.read_user(username)

    # Helper method that simplifies returning forms after user error.
    def give_create_form(username, session):
        message = session.pop('message', "")
        form = gatewayforms.CreateUG()
        t = loader.get_template('gateway_templates/create_user_gateway.html')
        c = RequestContext(request, {'username':username,'form':form, 'message':message})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.CreateUG(request.POST)
        if form.is_valid():
            if not form.cleaned_data['volume_name']:
                logging.info("DLFKJSDF")
                vol = None
            else:
                attrs = {"Volume.name ==":form.cleaned_data['volume_name'].strip().replace(" ", "_")}
                vols = db.list_volumes(attrs, limit=1)
                if vols:
                    vol = vols[0]
                else:
                    session['message'] = "No volume %s exists." % form.cleaned_data['volume_name']
                    return give_create_form(username, session)
                if (vol.volume_id not in user.volumes_r) and (vol.volume_id not in user.volumes_rw):
                    session['message'] = "Must have read rights to volume %s to create UG for it." % form.cleaned_data['volume_name']
                    return give_create_form(username, session)
                # Force update of UG version
                attrs = {"UG_version":1}

                try:
                   transaction( lambda: db.update_volume(vol.volume_id, **attrs) )
                except Exception as E:
                   session['message'] = "UG creation error: %s" % E
                   return give_create_form( username, session )

            try:
                # Prep kwargs
                kwargs = {}
                kwargs['read_write'] = form.cleaned_data['read_write']
                kwargs['ms_username'] = form.cleaned_data['g_name']
                kwargs['port'] = form.cleaned_data['port']
                kwargs['host'] = form.cleaned_data['host']
                kwargs['ms_password'] = form.cleaned_data['g_password']

                # Create
                new_ug = db.create_user_gateway(user, vol, **kwargs)
            except Exception as E:
                session['message'] = "UG creation error: %s" % E
                return give_create_form(username, session)

            session['new_change'] = "Your new gateway is ready."
            session['next_url'] = '/syn/UG/mygateways'
            session['next_message'] = "Click here to see your gateways."
            return HttpResponseRedirect('/syn/thanks/')
        else:
            # Prep returned form values (so they don't have to re-enter stuff)

            if 'g_name' in form.errors:
                oldname = ""
            else:
                oldname = request.POST['g_name']
            if 'volume_name' in form.errors:
                oldvolume_name = ""
            else:
                oldvolume_name = request.POST['volume_name']
            if 'host' in form.errors:
                oldhost = ""
            else:
                oldhost = request.POST['host']
            if 'port' in form.errors:
                oldport = ""
            else:
                oldport = request.POST['port']

            # Prep error message
            message = "Invalid form entry: "

            for k, v in form.errors.items():
                message = message + "\"" + k + "\"" + " -> " 
                for m in v:
                    message = message + m + " "

            # Give then the form again
            form = gatewayforms.CreateUG(initial={'g_name': oldname,
                                       'volume_name': oldvolume_name,
                                       'host': oldhost,
                                       'port': oldport,
                                       })
            t = loader.get_template('gateway_templates/create_user_gateway.html')
            c = RequestContext(request, {'username':username,'form':form, 'message':message})
            return HttpResponse(t.render(c))

    else:
        # Not a POST, give them blank form
        return give_create_form(username, session)

Example 34

Project: dirigible-spreadsheet
Source File: views.py
View license
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.
    
    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.
    
    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).
    
    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.
    
    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.
    
    **Required arguments**
    
    None.
    
    **Optional arguments**
    
    ``form_class``
        The form class to use for registration.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.
    
    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.
    
    ``success_url``
        The URL to redirect to on successful registration.
    
    ``template_name``
        A custom template to use.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = form.save(profile_callback=profile_callback)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.
            return HttpResponseRedirect(success_url or reverse('registration_complete'))
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 35

Project: tendenci
Source File: views.py
View license
@ssl_required
def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             event_id=None,
             extra_context=None):
    """
    Allow a new user to register an account.

    Following successful registration, issue a redirect; by default,
    this will be whatever URL corresponds to the named URL pattern
    ``registration_complete``, which will be
    ``/accounts/register/complete/`` if using the included URLConf. To
    change this, point that named pattern at another URL, or pass your
    preferred URL as the keyword argument ``success_url``.

    By default, ``registration.forms.RegistrationForm`` will be used
    as the registration form; to change this, pass a different form
    class as the ``form_class`` keyword argument. The form class you
    specify must have a method ``save`` which will create and return
    the new ``User``, and that method must accept the keyword argument
    ``profile_callback`` (see below).

    To enable creation of a site-specific user profile object for the
    new user, pass a function which will create the profile object as
    the keyword argument ``profile_callback``. See
    ``RegistrationManager.create_inactive_user`` in the file
    ``models.py`` for details on how to write this function.

    By default, use the template
    ``registration/registration_form.html``; to change this, pass the
    name of a template as the keyword argument ``template_name``.

    **Required arguments**

    None.

    **Optional arguments**

    ``form_class``
        The form class to use for registration.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``profile_callback``
        A function which will be used to create a site-specific
        profile instance for the new ``User``.

    ``success_url``
        The URL to redirect to on successful registration.

    ``template_name``
        A custom template to use.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    # check if this site allows self registration, if not, redirect to login page
    allow_self_registration = get_setting('module', 'users', 'selfregistration')
    if not allow_self_registration:
        return HttpResponseRedirect(reverse('auth_login'))

    form_params = {}
    if request.session.get('form_params', None):
        form_params = request.session.pop('form_params')

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES, **form_params)
        if form.is_valid():
            # This is for including a link in the reg email back to the event viewed
            event = None
            if event_id: # the user signed up via an event
                from tendenci.apps.events.models import Event
                event = get_object_or_404(Event, pk=event_id)

            new_user = form.save(profile_callback=profile_callback, event=event)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.

            # add to the default group(s)
            default_user_groups =[g.strip() for g in (get_setting('module', 'users', 'defaultusergroup')).split(',')]
            if default_user_groups:
                from tendenci.apps.user_groups.models import Group, GroupMembership
                from django.db.models import Q
                for group_name in default_user_groups:
                    groups = Group.objects.filter(Q(name=group_name) | Q(label=group_name)).filter(allow_self_add=1, status=1, status_detail='active')
                    if groups:
                        group = groups[0]
                    else:
                        # group doesnot exist, so create the group
                        group = Group()
                        group.name  = group_name
                        group.label = group_name
                        group.type = 'distribution'
                        group.show_as_option = 1
                        group.allow_self_add = 1
                        group.allow_self_remove = 1
                        group.creator = new_user
                        group.creator_username = new_user.username
                        group.owner =  new_user
                        group.owner_username = new_user.username
                        try:
                            group.save()
                        except:
                            group = None

                    if group:
                        gm = GroupMembership()
                        gm.group = group
                        gm.member = new_user
                        gm.creator_id = new_user.id
                        gm.creator_username = new_user.username
                        gm.owner_id =  new_user.id
                        gm.owner_username = new_user.username
                        gm.save()


            EventLog.objects.log(instance=new_user)

            return HttpResponseRedirect(success_url or reverse('registration_complete'))
        elif form.similar_email_found:
            messages.add_message(
                request, messages.INFO,
                _(u"An account already exists for the email %(email)s." % {
                    'email': request.POST.get('email_0') or request.POST.get('email_1')}))

            querystring = 'registration=True'
            return HttpResponseRedirect(reverse('auth_password_reset')+ "?%s" % querystring)

    else:
        allow_same_email = request.GET.get('registration_approved', False)
        form_params = {'allow_same_email' : allow_same_email }
        request.session['form_params'] = form_params
        form = form_class(**form_params)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

Example 36

Project: django-adminactions
Source File: mass_update.py
View license
def mass_update(modeladmin, request, queryset):  # noqa
    """
        mass update queryset
    """

    def not_required(field, **kwargs):
        """ force all fields as not required"""
        kwargs['required'] = False
        return field.formfield(**kwargs)

    def _doit():
        errors = {}
        updated = 0
        for record in queryset:
            for field_name, value_or_func in list(form.cleaned_data.items()):
                if callable(value_or_func):
                    old_value = getattr(record, field_name)
                    setattr(record, field_name, value_or_func(old_value))
                else:
                    setattr(record, field_name, value_or_func)
            if clean:
                record.clean()
            record.save()
            updated += 1
        if updated:
            messages.info(request, _("Updated %s records") % updated)

        if len(errors):
            messages.error(request, "%s records not updated due errors" % len(errors))
        adminaction_end.send(sender=modeladmin.model,
                             action='mass_update',
                             request=request,
                             queryset=queryset,
                             modeladmin=modeladmin,
                             form=form,
                             errors=errors,
                             updated=updated)

    opts = modeladmin.model._meta
    perm = "{0}.{1}".format(opts.app_label, get_permission_codename('adminactions_massupdate', opts))
    if not request.user.has_perm(perm):
        messages.error(request, _('Sorry you do not have rights to execute this action'))
        return

    try:
        adminaction_requested.send(sender=modeladmin.model,
                                   action='mass_update',
                                   request=request,
                                   queryset=queryset,
                                   modeladmin=modeladmin)
    except ActionInterrupted as e:
        messages.error(request, str(e))
        return

    # Allows to specified a custom mass update Form in the ModelAdmin
    mass_update_form = getattr(modeladmin, 'mass_update_form', MassUpdateForm)

    MForm = modelform_factory(modeladmin.model, form=mass_update_form,
                              exclude=('pk',),
                              formfield_callback=not_required)
    grouped = defaultdict(lambda: [])
    selected_fields = []
    initial = {'_selected_action': request.POST.getlist(helpers.ACTION_CHECKBOX_NAME),
               'select_across': request.POST.get('select_across') == '1',
               'action': 'mass_update'}

    if 'apply' in request.POST:
        form = MForm(request.POST)
        if form.is_valid():
            try:
                adminaction_start.send(sender=modeladmin.model,
                                       action='mass_update',
                                       request=request,
                                       queryset=queryset,
                                       modeladmin=modeladmin,
                                       form=form)
            except ActionInterrupted as e:
                messages.error(request, str(e))
                return HttpResponseRedirect(request.get_full_path())

            # need_transaction = form.cleaned_data.get('_unique_transaction', False)
            validate = form.cleaned_data.get('_validate', False)
            clean = form.cleaned_data.get('_clean', False)

            if validate:
                with compat.atomic():
                    _doit()

            else:
                values = {}
                for field_name, value in list(form.cleaned_data.items()):
                    if isinstance(form.fields[field_name], ModelMultipleChoiceField):
                        messages.error(request, "Unable no mass update ManyToManyField without 'validate'")
                        return HttpResponseRedirect(request.get_full_path())
                    elif callable(value):
                        messages.error(request, "Unable no mass update using operators without 'validate'")
                        return HttpResponseRedirect(request.get_full_path())
                    elif field_name not in ['_selected_action', '_validate', 'select_across', 'action',
                                            '_unique_transaction', '_clean']:
                        values[field_name] = value
                queryset.update(**values)

            return HttpResponseRedirect(request.get_full_path())
    else:
        initial.update({'action': 'mass_update', '_validate': 1})
        # form = MForm(initial=initial)
        prefill_with = request.POST.get('prefill-with', None)
        prefill_instance = None
        try:
            # Gets the instance directly from the queryset for data security
            prefill_instance = queryset.get(pk=prefill_with)
        except ObjectDoesNotExist:
            pass

        form = MForm(initial=initial, instance=prefill_instance)

    for el in queryset.all()[:10]:
        for f in modeladmin.model._meta.fields:
            if f.name not in form._no_sample_for:
                if hasattr(f, 'flatchoices') and f.flatchoices:
                    grouped[f.name] = list(dict(getattr(f, 'flatchoices')).values())
                elif hasattr(f, 'choices') and f.choices:
                    grouped[f.name] = list(dict(getattr(f, 'choices')).values())
                elif isinstance(f, df.BooleanField):
                    grouped[f.name] = [True, False]
                else:
                    value = getattr(el, f.name)
                    if value is not None and value not in grouped[f.name]:
                        grouped[f.name].append(value)
                    initial[f.name] = initial.get(f.name, value)

    adminForm = helpers.AdminForm(form, modeladmin.get_fieldsets(request), {}, [], model_admin=modeladmin)
    media = modeladmin.media + adminForm.media
    dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.date) else str(obj)
    tpl = 'adminactions/mass_update.html'
    ctx = {'adminform': adminForm,
           'form': form,
           'action_short_description': mass_update.short_description,
           'title': u"%s (%s)" % (
               mass_update.short_description.capitalize(),
               smart_text(modeladmin.opts.verbose_name_plural),
           ),
           'grouped': grouped,
           'fieldvalues': json.dumps(grouped, default=dthandler),
           'change': True,
           'selected_fields': selected_fields,
           'is_popup': False,
           'save_as': False,
           'has_delete_permission': False,
           'has_add_permission': False,
           'has_change_permission': True,
           'opts': modeladmin.model._meta,
           'app_label': modeladmin.model._meta.app_label,
           # 'action': 'mass_update',
           # 'select_across': request.POST.get('select_across')=='1',
           'media': mark_safe(media),
           'selection': queryset}
    if django.VERSION[:2] > (1, 7):
        ctx.update(modeladmin.admin_site.each_context(request))
    else:
        ctx.update(modeladmin.admin_site.each_context())

    if django.VERSION[:2] > (1, 8):
        return render(request, tpl, context=ctx)
    else:
        return render_to_response(tpl, RequestContext(request, ctx))

Example 37

Project: tendenci
Source File: views.py
View license
@is_enabled('forms')
def form_detail(request, slug, template="forms/form_detail.html"):
    """
    Display a built form and handle submission.
    """
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=slug)

    if not has_view_perm(request.user,'forms.view_form',form):
        raise Http403

    # If form has a recurring payment, make sure the user is logged in
    if form.recurring_payment:
        [email_field] = form.fields.filter(field_type__iexact='EmailVerificationField')[:1] or [None]
        if request.user.is_anonymous() and not email_field:
            # anonymous user - if we don't have the email field, redirect to login
            response = redirect('auth_login')
            response['Location'] += '?next=%s' % form.get_absolute_url()
            return response
        if request.user.is_superuser and not email_field:
            messages.add_message(request, messages.WARNING,
                    'Please edit the form to include an email field ' + \
                    'as it is required for setting up a recurring ' + \
                    'payment for anonymous users.')

    form_for_form = FormForForm(form, request.user, request.POST or None, request.FILES or None)
    for field in form_for_form.fields:
        field_default = request.GET.get(field, None)
        if field_default:
            form_for_form.fields[field].initial = field_default

    if request.method == "POST":
        if form_for_form.is_valid():
            entry = form_for_form.save()
            entry.entry_path = request.POST.get("entry_path", "")
            if request.user.is_anonymous():
                if entry.get_email_address():
                    emailfield = entry.get_email_address()
                    firstnamefield = entry.get_first_name()
                    lastnamefield = entry.get_last_name()
                    phonefield = entry.get_phone_number()
                    password = ''
                    for i in range(0, 10):
                        password += random.choice(string.ascii_lowercase + string.ascii_uppercase)

                    user_list = User.objects.filter(email=emailfield).order_by('-last_login')
                    if user_list:
                        anonymous_creator = user_list[0]
                    else:
                        anonymous_creator = User(username=emailfield[:30], email=emailfield,
                                                 first_name=firstnamefield, last_name=lastnamefield)
                        anonymous_creator.set_password(password)
                        anonymous_creator.is_active = False
                        anonymous_creator.save()
                        anonymous_profile = Profile(user=anonymous_creator, owner=anonymous_creator,
                                                    creator=anonymous_creator, phone=phonefield)
                        anonymous_profile.save()
                    entry.creator = anonymous_creator
            else:
                entry.creator = request.user
            entry.save()
            entry.set_group_subscribers()

            # Email
            subject = generate_email_subject(form, entry)
            email_headers = {}  # content type specified below
            if form.email_from:
                email_headers.update({'Reply-To':form.email_from})

            # Email to submitter
            # fields aren't included in submitter body to prevent spam
            submitter_body = generate_submitter_email_body(entry, form_for_form)
            email_from = form.email_from or settings.DEFAULT_FROM_EMAIL
            email_to = form_for_form.email_to()
            is_spam = Email.is_blocked(email_to)
            if is_spam:
                # log the spam
                description = "Email \"{0}\" blocked because it is listed in email_blocks.".format(email_to)
                EventLog.objects.log(instance=form, description=description)
                
                if form.completion_url:
                    return HttpResponseRedirect(form.completion_url)
                return redirect("form_sent", form.slug)
                
            email = Email()
            email.subject = subject
            email.reply_to = form.email_from

            if email_to and form.send_email and form.email_text:
                # Send message to the person who submitted the form.
                email.recipient = email_to
                email.body = submitter_body
                email.send(fail_silently=True)

            # Email copies to admin
            admin_body = generate_admin_email_body(entry, form_for_form)
            email_from = email_to or email_from # Send from the email entered.
            email_headers = {}  # Reset the email_headers
            email_headers.update({'Reply-To':email_from})
            email_copies = [e.strip() for e in form.email_copies.split(',') if e.strip()]

            subject = subject.encode(errors='ignore')
            email_recipients = entry.get_function_email_recipients()
            # reply_to of admin emails goes to submitter
            email.reply_to = email_to

            if email_copies or email_recipients:
                # prepare attachments
                attachments = []
                try:
                    for f in form_for_form.files.values():
                        f.seek(0)
                        attachments.append((f.name, f.read()))
                except ValueError:
                    attachments = []
                    for field_entry in entry.fields.all():
                        if field_entry.field.field_type == 'FileField':
                            try:
                                f = default_storage.open(field_entry.value)
                            except IOError:
                                pass
                            else:
                                f.seek(0)
                                attachments.append((f.name.split('/')[-1], f.read()))

                # Send message to the email addresses listed in the copies
                if email_copies:
                    email.body = admin_body
                    email.recipient = email_copies
                    email.send(fail_silently=True, attachments=attachments)

                # Email copies to recipient list indicated in the form
                if email_recipients:
                    email.body = admin_body
                    email.recipient = email_recipients
                    email.send(fail_silently=True, attachments=attachments)

            # payment redirect
            if (form.custom_payment or form.recurring_payment) and entry.pricing:
                # get the pricing's price, custom or otherwise
                price = entry.pricing.price or form_for_form.cleaned_data.get('custom_price')

                if form.recurring_payment:
                    if request.user.is_anonymous():
                        rp_user = entry.creator
                    else:
                        rp_user = request.user
                    billing_start_dt = datetime.datetime.now()
                    trial_period_start_dt = None
                    trial_period_end_dt = None
                    if entry.pricing.has_trial_period:
                        trial_period_start_dt = datetime.datetime.now()
                        trial_period_end_dt = trial_period_start_dt + datetime.timedelta(1)
                        billing_start_dt = trial_period_end_dt
                    # Create recurring payment
                    rp = RecurringPayment(
                             user=rp_user,
                             description=form.title,
                             billing_period=entry.pricing.billing_period,
                             billing_start_dt=billing_start_dt,
                             num_days=entry.pricing.num_days,
                             due_sore=entry.pricing.due_sore,
                             payment_amount=price,
                             taxable=entry.pricing.taxable,
                             tax_rate=entry.pricing.tax_rate,
                             has_trial_period=entry.pricing.has_trial_period,
                             trial_period_start_dt=trial_period_start_dt,
                             trial_period_end_dt=trial_period_end_dt,
                             trial_amount=entry.pricing.trial_amount,
                             creator=rp_user,
                             creator_username=rp_user.username,
                             owner=rp_user,
                             owner_username=rp_user.username,
                         )
                    rp.save()
                    rp.add_customer_profile()

                    # redirect to recurring payments
                    messages.add_message(request, messages.SUCCESS, _('Successful transaction.'))
                    return redirect('recurring_payment.view_account', rp.id, rp.guid)
                else:
                    # create the invoice
                    invoice = make_invoice_for_entry(entry, custom_price=price)
                    # log an event for invoice add

                    EventLog.objects.log(instance=form)

                    # redirect to billing form
                    return redirect('form_entry_payment', invoice.id, invoice.guid)

            # default redirect
            if form.completion_url:
                return HttpResponseRedirect(form.completion_url)
            return redirect("form_sent", form.slug)

    # set form's template to forms/base.html if no template or template doesn't exist
    if not form.template or not template_exists(form.template):
        form.template = "forms/base.html"

    # NOTE: Temporarily use forms/base.html for the meantime
    form.template = "forms/base.html"

    context = {
        "form": form,
        "form_for_form": form_for_form,
        'form_template': form.template,
    }
    return render_to_response(template, context, RequestContext(request))

Example 38

Project: virtmgr
Source File: views.py
View license
def index(request, host_id):

   	if not request.user.is_authenticated():
	   	return HttpResponseRedirect('/user/login')

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
			            type=type_err, 
			            message=msg, 
			            user_id=request.user.id
			            )
		error_msg.save()

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0

  	def vm_conn():
  		flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
	   	auth = [flags, creds, None]
		uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
	   	try:
		   	conn = libvirt.openAuth(uri, auth, 0)
		   	return conn
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_all_vm():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def get_all_stg():
		try:
			storages = []
			for name in conn.listStoragePools():
				storages.append(name)
			for name in conn.listDefinedStoragePools():
				storages.append(name)
			return storages
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_all_net():
		try:
			networks = []
			for name in conn.listNetworks():
				networks.append(name)
			for name in conn.listDefinedNetworks():
				networks.append(name)
			# Not support all distro but Fedora!!!
			#for ifcfg in conn.listInterfaces():
			#	if ifcfg != 'lo' and not re.findall("eth", ifcfg):
			#		networks.append(ifcfg)
			#for ifcfg in conn.listDefinedInterfaces():
			#	if ifcfg != 'lo' and not re.findall("eth", ifcfg):
			#		networks.append(ifcfg)
			return networks
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def find_all_iso():
		try:
			iso = []
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				stg.refresh(0)
				for img in stg.listVolumes():
					if re.findall(".iso", img) or re.findall(".ISO", img):
						iso.append(img)
			return iso
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def find_all_img():
		try:		
			disk = []
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				stg.refresh(0)
				for img in stg.listVolumes():
					if re.findall(".img", img) or re.findall(".IMG", img):
						disk.append(img)
			return disk
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def get_img_path(vol):
		try:
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				for img in stg.listVolumes():
					if vol == img:
						vl = stg.storageVolLookupByName(vol)
						return vl.path()
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_img_format(vol):
		try:
			for storage in storages:
				stg = conn.storagePoolLookupByName(storage)
				for img in stg.listVolumes():
					if vol == img:
						vl = stg.storageVolLookupByName(vol)
						xml = vl.XMLDesc(0)
						format = util.get_xml_path(xml, "/volume/target/format/@type")
						return format
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_cpus():
		try:
			return conn.getInfo()[2]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
	
	def get_mem():
		try:
			return conn.getInfo()[1]
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_emulator():
		try:
			emulator = []
			xml = conn.getCapabilities()
			arch = conn.getInfo()[0]
			if arch == 'x86_64':
				emulator.append(util.get_xml_path(xml,"/capabilities/guest[1]/arch/emulator"))
				emulator.append(util.get_xml_path(xml,"/capabilities/guest[2]/arch/emulator"))
			else:
				emulator = util.get_xml_path(xml,"/capabilities/guest/arch/emulator")
			return emulator
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	def get_machine():
		try:
			xml = conn.getCapabilities()
			machine = util.get_xml_path(xml,"/capabilities/guest/arch/machine/@canonical")
			return machine
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"
			
	def create_volume(stg_pool, img, size_max):
		try:
			size_max = int(size_max) * 1073741824
			xml = """
				<volume>
					<name>%s.img</name>
					<capacity>%s</capacity>
					<allocation>0</allocation>
					<target>
						<format type='qcow2'/>
					</target>
				</volume>""" % (img, size_max)
			stg = conn.storagePoolLookupByName(stg_pool)
			stg.createXML(xml,0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"
	
	def add_vm(name, mem, cpus, machine, emul, img, iso, bridge):
		try:
			arch = conn.getInfo()[0]
			if not iso:
				iso = ''
			memaloc = mem
			xml = """<domain type='kvm'>
					  <name>%s</name>
					  <memory>%s</memory>
					  <currentMemory>%s</currentMemory>
					  <vcpu>%s</vcpu>
					  <os>
					    <type arch='%s' machine='%s'>hvm</type>
					    <boot dev='hd'/>
					    <boot dev='cdrom'/>
					    <bootmenu enable='yes'/>
					  </os>
					  <features>
					    <acpi/>
					    <apic/>
					    <pae/>
					  </features>
					  <clock offset='utc'/>
					  <on_poweroff>destroy</on_poweroff>
					  <on_reboot>restart</on_reboot>
					  <on_crash>restart</on_crash>
					  <devices>""" % (name, mem, memaloc, cpus, arch, machine)
				
			if arch == 'x86_64':
				xml += """<emulator>%s</emulator>""" % (emul[1])
			else:
				xml += """<emulator>%s</emulator>""" % (emul)

			xml += """<disk type='file' device='disk'>
					      <driver name='qemu' type='qcow2'/>
					      <source file='%s'/>
					      <target dev='hda' bus='ide'/>
					    </disk>
					    <disk type='file' device='cdrom'>
					      <driver name='qemu' type='raw'/>
					      <source file='%s'/>
					      <target dev='hdc' bus='ide'/>
					      <readonly/>
					    </disk>
					    <controller type='ide' index='0'>
					      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
					    </controller>
					    """ % (img, iso)

			if re.findall("br", bridge):
				xml += """<interface type='bridge'>
						<source bridge='%s'/>""" % (bridge)
			else:
				xml += """<interface type='network'>
						<source network='%s'/>""" % (bridge)
				
			xml += """<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
					    </interface>
					    <input type='tablet' bus='usb'/>
					    <input type='mouse' bus='ps2'/>
					    <graphics type='vnc' port='-1' autoport='yes'/>
					    <video>
					      <model type='cirrus' vram='9216' heads='1'/>
					      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
					    </video>
					    <memballoon model='virtio'>
					      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
					    </memballoon>
					  </devices>
					</domain>"""
			conn.defineXML(xml)
			dom = conn.lookupByName(name)
			dom.setAutostart(1)
		except libvirt.libvirtError as e:
			add_error(e, 'libvirt')
			return "error"

	conn = vm_conn()

	if conn == "error":
		return HttpResponseRedirect('/overview/' + host_id + '/')

	errors = []
	cores = get_cpus()
	all_vm = get_all_vm()
	storages = get_all_stg()
	all_iso = find_all_iso()
	all_img = find_all_img()
	if all_iso is "error" or all_img is "error":
		msg = _('Storage pools are not available or are not active')
		errors.append(msg)	
	bridge = get_all_net()
	if bridge == "error":
		msg = _('Network pools are not available or are not active')
		errors.append(msg)			
	emul = get_emulator()
	machine = get_machine()
	addmem = get_mem()
	
	cpus = []
	for cpu in range(1,cores+1):
		cpus.append(cpu)

	if request.method == 'POST':
		name = request.POST.get('name','')
		setmem = request.POST.get('memory','')
		cpus = request.POST.get('cpus','')
		iso = request.POST.get('iso','')		
		img = request.POST.get('img','')
		netbr = request.POST.get('bridge','')
		setmem = int(setmem) * 1024
		hdd = get_img_path(img)
		cdrom = get_img_path(iso)
		hdd_frmt = get_img_format(img)
		simbol = re.search('[^a-zA-Z0-9\_]+', name)
		if name in all_vm:
			msg = _('This is the name of the virtual machine already exists')
			errors.append(msg)
		if len(name) > 20:
			msg = _('The name of the virtual machine must not exceed 20 characters')
			errors.append(msg)
		if simbol:
			msg = _('The name of the virtual machine must not contain any characters and Russian characters')
			errors.append(msg)
		if not request.POST.get('hdd','') and not img or img == 'error':
			msg = _('Images of the HDD to a virtual machine not available. You need to create an HDD image')
			errors.append(msg)
		if not name:
			msg = _('Enter the name of the virtual machine')
			errors.append(msg)
		if not errors:
			if request.POST.get('hdd',''):
				size = request.POST.get('hdd','')
				stg_pool = request.POST.get('stg_pool','')
				create_volume(stg_pool, name, size)
				img = name + '.img'
				hdd = get_img_path(img)
			if add_vm(name, setmem, cpus, machine, emul, hdd, cdrom, netbr) is 'error':
				msg = _('Hardware acceleration is not found')
				errors.append(msg)
			else:
				msg = _('Creating a virtual machine: ')
				msg = msg + name
				add_error(msg,'user')
				return HttpResponseRedirect('/vm/%s/%s/' % (host_id, name))


	conn.close()

	return render_to_response('newvm.html', locals())

Example 39

Project: tendenci
Source File: views.py
View license
@is_enabled('photos')
@flash_login_required
def photos_batch_add(request, photoset_id=0):
    """
    params: request, photoset_id
    returns: HttpResponse

    on flash request:
        photoset_id is passed via request.POST
        and received as type unicode; i convert to type integer
    on http request:
        photoset_id is passed via url
    """
    import uuid
    from django.db.models import Max
    from tendenci.apps.perms.object_perms import ObjectPermission

    # photoset permission required to add photos
    if not has_perm(request.user, 'photos.add_photoset'):
        raise Http403

    if request.method == 'POST':
        for field_name in request.FILES:
            uploaded_file = request.FILES[field_name]

            # use file to create title; remove extension
            filename, extension = os.path.splitext(uploaded_file.name)
            request.POST.update({'title': filename, })

            # clean filename; alphanumeric with dashes
            filename = re.sub(r'[^a-zA-Z0-9._]+', '-', filename)

            # truncate; make unique; append extension
            request.FILES[field_name].name = \
                filename[:70] + '-' + unicode(uuid.uuid1())[:5] + extension

            # photoset_id set in swfupload
            photoset_id = int(request.POST["photoset_id"])

            request.POST.update({
                'owner': request.user.id,
                'owner_username': unicode(request.user),
                'creator_username': unicode(request.user),
                'status': True,
                'status_detail': 'active',
            })

            photo_form = PhotoUploadForm(request.POST, request.FILES, user=request.user)

            if photo_form.is_valid():
                # save photo
                photo = photo_form.save(commit=False)
                photo.creator = request.user
                photo.member = request.user
                photo.safetylevel = 3
                photo.allow_anonymous_view = True

                position_max = Image.objects.filter(
                    photoset=photoset_id).aggregate(Max('position'))['position__max'] or 0

                photo.position = position_max + 1

                # update all permissions and save the model
                photo = update_perms_and_save(request, photo_form, photo)

                EventLog.objects.log(**{
                    'event_id': 990100,
                    'event_data': '%s (%d) added by %s' % (photo._meta.object_name, photo.pk, request.user),
                    'description': '%s added' % photo._meta.object_name,
                    'user': request.user,
                    'request': request,
                    'instance': photo,
                })

                # add to photo set if photo set is specified
                if photoset_id:
                    photo_set = get_object_or_404(PhotoSet, id=photoset_id)
                    photo_set.image_set.add(photo)

                privacy = get_privacy_settings(photo_set)

                # photo privacy = album privacy
                for k, v in privacy.items():
                    setattr(photo, k, v)

                photo.save()

                # photo group perms = album group perms
                group_perms = photo_set.perms.filter(group__isnull=False).values_list('group', 'codename')
                group_perms = tuple([(unicode(g), c.split('_')[0]) for g, c in group_perms])
                ObjectPermission.objects.assign_group(group_perms, photo)

                # serialize queryset
                data = serializers.serialize("json", Image.objects.filter(id=photo.id))

                cache_image = Popen(["python", "manage.py", "precache_photo", str(photo.pk)])

                # returning a response of "ok" (flash likes this)
                # response is for flash, not humans
                return HttpResponse(data, content_type="text/plain")
            else:
                return HttpResponse("photo is not valid", content_type="text/plain")

    else:
        if not photoset_id:
            HttpResponseRedirect(reverse('photoset_latest'))
        photo_set = get_object_or_404(PhotoSet, id=photoset_id)

        photo_limit = get_setting('module', 'photos', 'photolimit')
        try:
            photo_limit = int(photo_limit)
        except ValueError:
            # default limit for photo set images 150
            photo_limit = 150
        image_slot_left = photo_limit - photo_set.image_set.count()

        # show the upload UI
        return render_to_response('photos/batch-add.html', {
            "photoset_id": photoset_id,
            "photo_set": photo_set,
            "csrf_token": csrf_get_token(request),
            "image_slot_left": image_slot_left,
             },
            context_instance=RequestContext(request))

Example 40

Project: django-concurrency
Source File: admin.py
View license
    def response_action(self, request, queryset):  # noqa
        """
        Handle an admin action. This is called if a request is POSTed to the
        changelist; it returns an HttpResponse if the action was handled, and
        None otherwise.
        """
        # There can be multiple action forms on the page (at the top
        # and bottom of the change list, for example). Get the action
        # whose button was pushed.
        try:
            action_index = int(request.POST.get('index', 0))
        except ValueError:  # pragma: no cover
            action_index = 0

        # Construct the action form.
        data = request.POST.copy()
        data.pop(helpers.ACTION_CHECKBOX_NAME, None)
        data.pop("index", None)

        # Use the action whose button was pushed
        try:
            data.update({'action': data.getlist('action')[action_index]})
        except IndexError:
            # If we didn't get an action from the chosen form that's invalid
            # POST data, so by deleting action it'll fail the validation check
            # below. So no need to do anything here
            pass

        action_form = self.action_form(data, auto_id=None)
        action_form.fields['action'].choices = self.get_action_choices(request)

        # If the form's valid we can handle the action.
        if action_form.is_valid():
            action = action_form.cleaned_data['action']
            func, name, description = self.get_actions(request)[action]

            # Get the list of selected PKs. If nothing's selected, we can't
            # perform an action on it, so bail.
            if action_form.cleaned_data['select_across']:
                selected = ALL
            else:
                selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

            revision_field = self.model._concurrencymeta.field
            if not selected:
                return None

            if self.check_concurrent_action:
                self.delete_selected_confirmation_template = self.get_confirmation_template()

                # If select_across we have to avoid the use of concurrency
                if selected is not ALL:
                    filters = []
                    for x in selected:
                        try:
                            pk, version = x.split(",")
                        except ValueError:
                            raise ImproperlyConfigured('`ConcurrencyActionMixin` error.'
                                                       'A tuple with `primary_key, version_number` '
                                                       'expected:  `%s` found' % x)
                        filters.append(Q(**{'pk': pk,
                                            revision_field.attname: version}))

                    queryset = queryset.filter(reduce(operator.or_, filters))
                    if len(selected) != queryset.count():
                        messages.error(request, 'One or more record were updated. '
                                                '(Probably by other user) '
                                                'The execution was aborted.')
                        return HttpResponseRedirect(".")
                else:
                    messages.warning(request, 'Selecting all records, you will avoid the concurrency check')

            response = func(self, request, queryset)

            # Actions may return an HttpResponse, which will be used as the
            # response from the POST. If not, we'll be a good little HTTP
            # citizen and redirect back to the changelist page.
            if isinstance(response, HttpResponse):
                return response
            else:
                return HttpResponseRedirect(".")

Example 41

Project: WIPSTER
Source File: views.py
View license
def sample_page(request,md5):

##################
#### Set Vars ####
##################

#    sample = get_object_or_404(Sample, md5=md5)
    sample = Sample.objects.filter(md5=md5)
    savename = handler.get_savename(sample[sample.count()-1])
    savename = 'samples/'+md5+'/'+savename
    ta_submit = ""
    plaintext = {'vt_short': [],
                 'vt_nums': ""}

    extra_params = "&md5="+md5

    # Process ticket #
    ticket = sample[sample.count()-1].ticket
    zeros = '0' * (12 - len(ticket))
    plaintext['ticket'] = "TICKET" + zeros + ticket
    
    # Process VT #
    if sample[sample.count()-1].vt_short:
        vt_plain_res = sample[sample.count()-1].vt_short
        if "Results:" in vt_plain_res:
            vt_res_split = vt_plain_res.split("\r\n")
            vt_nums_split = vt_res_split[0].split("\t")
            if vt_nums_split > 1:
                plaintext['vt_nums'] = vt_nums_split[1]
            vt_split1 = vt_plain_res.split("\r\n\r\n")
            if len(vt_split1) > 1:
                vt_short_line = vt_split1[1].split("\r\n")
                for line in vt_short_line:
                    if line:
                        vendor_detect_split = line.split(":\t")
                        space_length = " " * (10 - len(vendor_detect_split[0]))
                        vendor_fix = vendor_detect_split[0] + space_length + ":    "
                        plaintext['vt_short'].append({'vendor': vendor_fix,
                                                      'detect': vendor_detect_split[1]})
    #debugerror

################################################
#### Process ThreatAnalyzer POST Submission ####
################################################

    if request.method=="POST" and ta_use:
        if 'ta_submit' in request.POST:
            if request.POST['ta_submit']:

                ta_submit = threatanalyzer.submit_to_ta(md5, savename)

                current_page = "/sanalysis/md5/"+md5+"/"
                return HttpResponseRedirect(current_page)


#### Process ThreatAnalyzer Data ####

    if ta_use:
        ta_analyses, ta_risks, ta_network, ta_ips, ta_domains, ta_commands, ta_dropped = threatanalyzer.get_ta_analyses(md5, extra_params=extra_params)
    else:
        ta_analyses=ta_risks=ta_network = ""
        ta_ips=ta_domains=ta_commands = []

    #Automatically submit to ThreatAnalyzer if ta_autosubmit == True and there is no existing analyses
    if ta_use and ta_autosubmit and "HTTP Error 404" in ta_analyses:
        ta_submit = threatanalyzer.submit_to_ta(md5, savename)    


############################
#### Process CRITs Data ####
############################

    crits_vt = {}
    crits_ta = {}
    crits_dict = {}
    crits_submit = ""
    crits_rel_trace = ""

    if crits_use:
        if sample[sample.count()-1].vt_short:
            vt_short_res = sample[sample.count()-1].vt_short
            crits_vt = crits.crits_vt(vt_short_res)
            if not (ta_ips or ta_domains or ta_commands):
                crits_dict = crits_vt

        if ta_use and (ta_ips or ta_domains or ta_commands):
            crits_ta = crits.crits_parse(ta_ips, ta_domains, ta_commands, ta_dropped)
            if not sample[sample.count()-1].vt_short:    
                crits_dict = crits_ta

        if crits_vt and crits_ta:
            crits_dict.clear()
            crits_dict = crits_vt.copy()
            crits_dict.update(crits_ta)

        crits_dict['page'] = crits_base+"/samples/details/"+sample[sample.count()-1].md5+"/"


    else:
        crits_dict = { 'crits_ips' : [],
                       'crits_domains': [],
                       'crits_uas' : [],
                       'crits_vts' : [],
                       'crits_commands' : [],
                       'page': ""}

############################
#### Process CRITs Form ####
############################

    if request.method=="POST" and crits_use:
        #If submitting new data to CRITs
        if 'crits_submit' in request.POST:
            if request.POST['crits_submit']:
                crits_submit = crits.submit_to_crits(request.POST, sample[sample.count()-1], crits_ta, savename=savename)
        #If trying to get relationships from CRITs DB
        if 'crits_rel_trace' in request.POST:
            if request.POST['crits_rel_trace']:
                
                #### Set the variables for the trace
                
                #Get all tickets related to this sample from the WIPSTER DB
                db_tickets = []
                for i in sample:
                    if i.ticket and i.ticket not in db_tickets:
                        db_tickets.append(i.ticket)
                
                crits_rel_trace_vars = {
                            'md5' : sample[sample.count()-1].md5,
                            'db_tickets' : db_tickets,
                            'depth' : crits_depth,
                            'crits_page' : crits_page,
                            'crits_base' : crits_base,
                            'crits_login' : crits_login,
                            'api_key': crits_api_key,
                            'username': crits_username,
                            'type': "Sample",
                            'cid': ''
                       }
                       
                #Get the relationships for the page display
                crits_rel_trace = crits_relationships.trace_crits_relationships(crits_rel_trace_vars)
                if not crits_rel_trace:
                    crits_rel_trace = "No potentially related tickets were found that are not currently associated with this sample."

    #If crits_autosubmit == True, all samples and tickets will be added to CRITs and related to eachother
    first_upload = request.GET.get('upload', '')
    if crits_use and crits_autosubmit and request.method!="POST" and first_upload:
        request.POST = {}
        crits_submit = crits.submit_to_crits(request.POST, sample[sample.count()-1], crits_ta, savename=savename)

#            current_page = "/sanalysis/md5/"+md5+"/"
#            return HttpResponseRedirect(current_page)

##########################
#### RENDER MAIN PAGE ####
##########################


    return render(request, 'sanalysis/sample_page.html', {'sample': sample,
                                                          'savename': savename,
                                                          'plaintext': plaintext,
                                                          'ta_use': ta_use,
                                                          'ta_analyses': ta_analyses,
                                                          'ta_risks': ta_risks,
                                                          'ta_network': ta_network,
                                                          'ta_ips': ta_ips,
                                                          'ta_domains': ta_domains,
                                                          'ta_commands': ta_commands,
                                                          'ta_dropped': ta_dropped,
                                                          'ta_submit': ta_submit,
                                                          'crits_use': crits_use,
                                                          'crits': crits_dict,
                                                          'crits_submit': crits_submit, 
                                                          'crits_rel_trace': crits_rel_trace,})

Example 42

Project: talk.org
Source File: comments.py
View license
def post_comment(request, extra_context=None, context_processors=None):
    """
    Post a comment

    Redirects to the `comments.comments.comment_was_posted` view upon success.

    Templates: `comment_preview`
    Context:
        comment
            the comment being posted
        comment_form
            the comment form
        options
            comment options
        target
            comment target
        hash
            security hash (must be included in a posted form to succesfully
            post a comment).
        rating_options
            comment ratings options
        ratings_optional
            are ratings optional?
        ratings_required
            are ratings required?
        rating_range
            range of ratings
        rating_choices
            choice of ratings
    """
    if extra_context is None: extra_context = {}
    if not request.POST:
        raise Http404, _("Only POSTs are allowed")
    try:
        options, target, security_hash = request.POST['options'], request.POST['target'], request.POST['gonzo']
    except KeyError:
        raise Http404, _("One or more of the required fields wasn't submitted")
    photo_options = request.POST.get('photo_options', '')
    rating_options = normalize_newlines(request.POST.get('rating_options', ''))
    if Comment.objects.get_security_hash(options, photo_options, rating_options, target) != security_hash:
        raise Http404, _("Somebody tampered with the comment form (security violation)")
    # Now we can be assured the data is valid.
    if rating_options:
        rating_range, rating_choices = Comment.objects.get_rating_options(base64.decodestring(rating_options))
    else:
        rating_range, rating_choices = [], []
    content_type_id, object_id = target.split(':') # target is something like '52:5157'
    try:
        obj = ContentType.objects.get(pk=content_type_id).get_object_for_this_type(pk=object_id)
    except ObjectDoesNotExist:
        raise Http404, _("The comment form had an invalid 'target' parameter -- the object ID was invalid")
    option_list = options.split(',') # options is something like 'pa,ra'
    new_data = request.POST.copy()
    new_data['content_type_id'] = content_type_id
    new_data['object_id'] = object_id
    new_data['ip_address'] = request.META.get('REMOTE_ADDR')
    new_data['is_public'] = IS_PUBLIC in option_list
    manipulator = PublicCommentManipulator(request.user,
        ratings_required=RATINGS_REQUIRED in option_list,
        ratings_range=rating_range,
        num_rating_choices=len(rating_choices))
    errors = manipulator.get_validation_errors(new_data)
    # If user gave correct username/password and wasn't already logged in, log them in
    # so they don't have to enter a username/password again.
    if manipulator.get_user() and not manipulator.get_user().is_authenticated() and 'password' in new_data and manipulator.get_user().check_password(new_data['password']):
        from django.contrib.auth import login
        login(request, manipulator.get_user())
    if errors or 'preview' in request.POST:
        class CommentFormWrapper(oldforms.FormWrapper):
            def __init__(self, manipulator, new_data, errors, rating_choices):
                oldforms.FormWrapper.__init__(self, manipulator, new_data, errors)
                self.rating_choices = rating_choices
            def ratings(self):
                field_list = [self['rating%d' % (i+1)] for i in range(len(rating_choices))]
                for i, f in enumerate(field_list):
                    f.choice = rating_choices[i]
                return field_list
        comment = errors and '' or manipulator.get_comment(new_data)
        comment_form = CommentFormWrapper(manipulator, new_data, errors, rating_choices)
        return render_to_response('comments/preview.html', {
            'comment': comment,
            'comment_form': comment_form,
            'options': options,
            'target': target,
            'hash': security_hash,
            'rating_options': rating_options,
            'ratings_optional': RATINGS_OPTIONAL in option_list,
            'ratings_required': RATINGS_REQUIRED in option_list,
            'rating_range': rating_range,
            'rating_choices': rating_choices,
        }, context_instance=RequestContext(request, extra_context, context_processors))
    elif 'post' in request.POST:
        # If the IP is banned, mail the admins, do NOT save the comment, and
        # serve up the "Thanks for posting" page as if the comment WAS posted.
        if request.META['REMOTE_ADDR'] in settings.BANNED_IPS:
            mail_admins("Banned IP attempted to post comment", smart_unicode(request.POST) + "\n\n" + str(request.META))
        else:
            manipulator.do_html2python(new_data)
            comment = manipulator.save(new_data)
        return HttpResponseRedirect("../posted/?c=%s:%s" % (content_type_id, object_id))
    else:
        raise Http404, _("The comment form didn't provide either 'preview' or 'post'")

Example 43

Project: hubplus
Source File: views.py
View license
@login_required
@secure_resource(TgGroup)
def edit_resource(request, group, resource_name,  
                  template_name='plus_resources/upload.html', success_url=None, current_app="plus_groups", **kwargs) :


    if not group :
        raise Http404(_('This group does not exist'))
 
    try:
        secure_upload = Resource.objects.plus_get(request.user, name=resource_name, in_agent=group.get_ref())
    except Resource.DoesNotExist:
        raise Http404

    if secure_upload.name :
        old_name = secure_upload.name
    else :
        old_name = ''

    try:
        secure_upload.get_all_sliders
        perms_bool = True
    except PlusPermissionsNoAccessException:
        perms_bool = False

    if request.POST:
        post_kwargs = request.POST.copy()
        post_kwargs['obj'] = secure_upload

        if "delete_submit" in post_kwargs :
            if post_kwargs.has_key('delete_check') :
                secure_upload.delete()
                return HttpResponseRedirect(reverse(current_app + ':group', args=[group.id]))

        if "move_resource_submit" in post_kwargs :
            form = MoveResourceForm(post_kwargs)
            form.user = request.user # essential, user is checked inside form validation
            if form.is_valid() :
                new_parent_group = form.cleaned_data['new_parent_group']
                try :
                    secure_upload.move_to_new_group(new_parent_group)
                except Exception, e :
                    print e

                return HttpResponseRedirect(reverse(current_app + ':group', args=[form.cleaned_data['new_parent_group'].id]))

        form = UploadFileForm(post_kwargs, request.FILES, user=request.user)

        if form.is_valid():
            a_file = form.cleaned_data['resource']

            resource = update_attributes(secure_upload, request.user,
                                         title = form.cleaned_data['title'],
                                         name  = form.cleaned_data['name'],
                                         license = form.cleaned_data['license'],
                                         author = form.cleaned_data['author'],
                                         description = form.cleaned_data['description'],
                                         resource = a_file)
   
            resource.stub = False
            resource.in_agent = group.get_ref()

            # don't allow name to change as this affects the url
            if old_name :
                resource.name = old_name
            resource.save()
            
            if not success_url :
                success_url = reverse(current_app + ':view_Resource', args=(group.id, resource.name))
           
            from apps.plus_feed.models import FeedItem
            FeedItem.post_UPLOAD(request.user, resource)

            return HttpResponseRedirect(success_url)
                 
        else:
            pass

    else :
        form = UploadFileForm()
        form.data['title'] = secure_upload.title
        form.data['name'] = secure_upload.name
    
    tags = get_tags_for_object(secure_upload, request.user)

    return render_to_response(template_name, {
        'upload': TemplateSecureWrapper(secure_upload),
        'resource':TemplateSecureWrapper(secure_upload), # let's us use resource_common included template
        'data' : form.data,
        'errors': form.errors,
        'form_action':'',
        'form_encoding':'enctype=multipart/form-data',
        'permissions':perms_bool,
        'tags':tags,
        'pages':[p.get_ref() for p in group.get_resources_of_class(WikiPage)],
        'pages_listings_args':listing_args('home', 'home', '')
        
    }, context_instance=RequestContext(request, current_app=current_app))

Example 44

Project: django-wakawaka
Source File: views.py
View license
def edit(request, slug, rev_id=None, template_name='wakawaka/edit.html',
         extra_context=None, wiki_page_form=WikiPageForm,
         wiki_delete_form=DeleteWikiPageForm):
    """
    Displays the form for editing and deleting a page.
    """
    if extra_context is None:
        extra_context = {}

    # Get the page for slug and get a specific revision, if given
    try:
        queryset = WikiPage.objects.all()
        page = queryset.get(slug=slug)
        rev = page.current
        initial = {'content': page.current.content}

        # Do not allow editing wiki pages if the user has no permission
        if not request.user.has_perms(('wakawaka.change_wikipage', 'wakawaka.change_revision' )):
            return HttpResponseForbidden(ugettext('You don\'t have permission to edit pages.'))

        if rev_id:
            # There is a specific revision, fetch this
            rev_specific = Revision.objects.get(pk=rev_id)
            if rev.pk != rev_specific.pk:
                rev = rev_specific
                rev.is_not_current = True
                initial = {'content': rev.content, 'message': _('Reverted to "%s"' % rev.message)}


    # This page does not exist, create a dummy page
    # Note that it's not saved here
    except WikiPage.DoesNotExist:
        
        # Do not allow adding wiki pages if the user has no permission
        if not request.user.has_perms(('wakawaka.add_wikipage', 'wakawaka.add_revision',)):
            return HttpResponseForbidden(ugettext('You don\'t have permission to add wiki pages.'))

        page = WikiPage(slug=slug)
        page.is_initial = True
        rev = None
        initial = {'content': _('Describe your new page %s here...' % slug),
                   'message': _('Initial revision')}

    # Don't display the delete form if the user has nor permission
    delete_form = None
    # The user has permission, then do
    if request.user.has_perm('wakawaka.delete_wikipage') or \
       request.user.has_perm('wakawaka.delete_revision'):
        delete_form = wiki_delete_form(request)
        if request.method == 'POST' and request.POST.get('delete'):
            delete_form = wiki_delete_form(request, request.POST)
            if delete_form.is_valid():
                return delete_form.delete_wiki(request, page, rev)

    # Page add/edit form
    form = wiki_page_form(initial=initial)
    if request.method == 'POST':
        form = wiki_page_form(data=request.POST)
        if form.is_valid():
            # Check if the content is changed, except there is a rev_id and the
            # user possibly only reverted the HEAD to it
            if not rev_id and initial['content'] == form.cleaned_data['content']:
                form.errors['content'] = (_('You have made no changes!'),)

            # Save the form and redirect to the page view
            else:
                try:
                    # Check that the page already exist
                    queryset = WikiPage.objects.all()
                    page = queryset.get(slug=slug)
                except WikiPage.DoesNotExist:
                    # Must be a new one, create that page
                    page = WikiPage(slug=slug)
                    page.save()

                form.save(request, page)
                
                kwargs = {
                    'slug': page.slug,
                }
                
                redirect_to = reverse('wakawaka_page', kwargs=kwargs)
                messages.success(request, ugettext('Your changes to %s were saved' % page.slug))
                return HttpResponseRedirect(redirect_to)

    template_context = {
        'form': form,
        'delete_form': delete_form,
        'page': page,
        'rev': rev,
    }
    template_context.update(extra_context)
    return render_to_response(template_name, template_context,
                              RequestContext(request))

Example 45

Project: transifex
Source File: views.py
View license
@login_required
def translate(request, project_slug, lang_code, resource_slug=None,
                     *args, **kwargs):
    """
    Main lotte view.
    """

    # Permissions handling
    # Project should always be available
    project = get_object_or_404(Project, slug=project_slug)
    team = Team.objects.get_or_none(project, lang_code)
    check = ProjectPermission(request.user)
    if not check.submit_translations(team or project) and not\
        check.maintain(project):
        return permission_denied(request)

    resources = []
    if resource_slug:
        resource_list = [get_object_or_404(Resource, slug=resource_slug,
            project=project)]
    else:
        resource_list = Resource.objects.filter(project=project)

        # Return a page explaining that the project has multiple source langs and
        # cannot be translated as a whole.
        if resource_list.values('source_language').distinct().count() > 1:
            messages.info(request,_(
                          "There are multiple source languages for this project. "
                          "You will only be able to translate resources for one "
                          "source language at a time."))
            return HttpResponseRedirect(reverse('project_detail',
                                        args=[project_slug]),)

    # Filter resources that are not accepting translations
    for resource in resource_list:
        if resource.accept_translations:
            resources.append(resource)

    # If no resource accepting translations, raise a 403
    if not resources:
        return permission_denied(request)

    target_language = Language.objects.by_code_or_alias_or_404(lang_code)

    # If it is an attempt to edit the source language, redirect the user to
    # resource_detail and show him a message explaining the reason.
    if target_language == get_source_language(resources):
        messages.error(request,_(
                       "Cannot edit the source language because this would "
                       "result in translation mismatches! If you want to "
                       "update the source strings consider using the transifex "
                       "command-line client."))
        if resource_slug:
            return HttpResponseRedirect(reverse('resource_detail',
                                                args=[project_slug,
                                                      resource_slug]),)
        else:
            return HttpResponseRedirect(reverse('project_detail',
                                                args=[project_slug]),)

    total_strings = SourceEntity.objects.filter(
        resource__in = resources).count()

    translated_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5).count()

    reviewed_strings = Translation.objects.filter(
        resource__in=resources,
        language=target_language,
        source_entity__pluralized=False,
        rule=5,
        reviewed=True).count()

    # Include counting of pluralized entities
    for pluralized_entity in SourceEntity.objects.filter(resource__in = resources,
                                                         pluralized=True):
        plurals_translated = Translation.objects.filter(
            language=target_language,
            source_entity=pluralized_entity).count()
        if plurals_translated == len(target_language.get_pluralrules()):
            translated_strings += 1

    if len(resources) > 1:
        translation_resource = None
    else:
        translation_resource = resources[0]

    contributors = User.objects.filter(pk__in=Translation.objects.filter(
        resource__in = resources,
        language = target_language,
        rule = 5).values_list("user", flat=True))

    lotte_init.send(None, request=request, resources=resources,
        language=target_language)

    if target_language in [team.language for team in project.available_teams]:
        team_language = True
    else:
        team_language = False

    GtModel = get_model('gtranslate', 'Gtranslate')
    try:
        auto_translate = GtModel.objects.get(project=project)
    except GtModel.DoesNotExist:
        auto_translate = None
    """
    if cache.get('lotte_%s' % request.session.session_key, None):
        cache.delete('lotte_%s' % request.session.session_key)
    """

    #Set rtl to True if target_language is an RTL language
    rtl = False
    if target_language.code in settings.RTL_LANGUAGE_CODES:
        rtl = True

    return render_to_response("translate.html", {
        'project': project,
        'resource': translation_resource,
        'target_language': target_language,
        'translated_strings': translated_strings,
        'reviewed_strings': reviewed_strings,
        'untranslated_strings': total_strings - translated_strings,
        'contributors': contributors,
        'resources': resources,
        'resource_slug': resource_slug,
        'languages': Language.objects.all(),
        'auto_translate': auto_translate,
        'spellcheck_supported_langs': SPELLCHECK_SUPPORTED_LANGS,
        'team_language': team_language,
        'RTL': rtl,
    }, context_instance = RequestContext(request))

Example 46

Project: virtmgr
Source File: views.py
View license
def snapshot(request, host_id, vname):

	if not request.user.is_authenticated():
		return HttpResponseRedirect('/')

	kvm_host = Host.objects.get(user=request.user.id, id=host_id)

	def add_error(msg, type_err):
		error_msg = Log(host_id=host_id, 
			            type=type_err, 
			            message=msg, 
			            user_id=request.user.id
			            )
		error_msg.save()

	def get_vms():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_vm_snapshots():
		try:
			vname = {}
			for id in conn.listDomainsID():
				id = int(id)
				dom = conn.lookupByID(id)
				if dom.snapshotNum(0) != 0:
					vname[dom.name()] = dom.info()[0]
			for id in conn.listDefinedDomains():
				dom = conn.lookupByName(id)
				if dom.snapshotNum(0) != 0:
					vname[dom.name()] = dom.info()[0]
			return vname
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def vm_conn():
	   	try:
			flags = [libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE]
	  		auth = [flags, creds, None]
			uri = 'qemu+tcp://' + kvm_host.ipaddr + '/system'
		   	conn = libvirt.openAuth(uri, auth, 0)
		   	return conn
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	if not kvm_host.login or not kvm_host.passwd:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = request.session['login_kvm']
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = request.session['passwd_kvm']
				else:
					return -1
			return 0
	else:
		def creds(credentials, user_data):
			for credential in credentials:
				if credential[0] == libvirt.VIR_CRED_AUTHNAME:
					credential[4] = kvm_host.login
					if len(credential[4]) == 0:
						credential[4] = credential[3]
				elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
					credential[4] = kvm_host.passwd
				else:
					return -1
			return 0

	def get_dom(vname):
		try:
			dom = conn.lookupByName(vname)
			return dom
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def get_snapshots():
		try:
			snapshots = {}
			all_snapshot = dom.snapshotListNames(0)
			for snapshot in all_snapshot:
				snapshots[snapshot] = (datetime.fromtimestamp(int(snapshot)), dom.info()[0])
			return snapshots
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def del_snapshot(name_snap):
		try:
			snap = dom.snapshotLookupByName(name_snap,0)
			snap.delete(0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	def revert_snapshot(name_snap):
		try:
			snap = dom.snapshotLookupByName(name_snap,0)
			dom.revertToSnapshot(snap,0)
		except libvirt.libvirtError as e:
			add_error(e,'libvirt')
			return "error"

	conn = vm_conn()
	all_vm_snapshots = get_vm_snapshots()
	dom = get_dom(vname)
	vm_snapshot = get_snapshots()
	all_vm = get_vms()

	if not vm_snapshot:
		return HttpResponseRedirect('/snapshot/%s/' % (host_id))

	if request.method == 'POST':
		if request.POST.get('delete',''):
			name = request.POST.get('name','')
			msg = _('Delete snapshot VM: ')
			msg = msg + vname + ' => ' + name
			add_error(msg,'user')
			del_snapshot(name)
			return HttpResponseRedirect('/snapshot/%s/%s/' % (host_id, vname))
		if request.POST.get('revert',''):
			name = request.POST.get('name','')
			msg = _('Revert snapshot VM: ')
			msg = msg + vname + ' => ' + name
			add_error(msg,'user')
        	revert_snapshot(name)
        	message = _('Successful revert snapshot: ')
        	message = message + name

	conn.close()

	return render_to_response('snapshot.html', locals())

Example 47

Project: logtacts
Source File: views.py
View license
@csrf_exempt
def sms(request):
    if request.method == 'GET':
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        overall_start = time.time()
        cache_key = request.POST.get('From')
        co_number = request.POST.get('To')
        message = request.POST.get('Body').strip()
        if not cache_key:
            raise Http404()
        flow_state = cache.get(cache_key)
        if flow_state:
            if message.lower() == 'done':
                cache.delete(cache_key)
                return help_message()
            if flow_state == QUERY_ACCOUNT:
                if message.lower() in ('yes', 'yep'):
                    cache.set(cache_key, GET_EMAIL, CACHE_TIMEOUT)
                    return create_message(
                        "Ok, what's the email address on your account?",
                        to=cache_key, sender=co_number,
                    )
                else:
                    cache.delete(cache_key)
                    return create_message(
                        "Ok! Please go to https://www.contactotter.com to create an account.",
                        to=cache_key, sender=co_number,
                    )
            if flow_state == GET_EMAIL:
                try:
                    # TODO: Send a confirmation email for connecting phone
                    user = User.objects.get(email=message.lower())
                    profile, _ = Profile.objects.get_or_create(user=user)
                    profile.phone_number = cache_key
                    profile.save()
                    cache.delete(cache_key)
                    return create_message(
                        "Ok! Your phone is connected to your account.",
                        to=cache_key, sender=co_number,
                    )
                except User.DoesNotExist:
                    cache.delete(cache_key)
                    return create_message(
                        "We couldn't find an account for that email. Please go to https://www.contactotter.com to create one",
                        to=cache_key, sender=co_number,
                    )
        user, book = get_user_objects_from_message(request.POST)
        if not user or not book:
            cache.set(cache_key, QUERY_ACCOUNT, CACHE_TIMEOUT)
            return create_message(
                "Hmm... I can't find an account with this number. Do you have a ContactOtter account?",
                to=cache_key, sender=co_number,
            )

        if flow_state:
            if flow_state.startswith('log'):
                name = ':'.join(flow_state.split(':')[1:])
                contacts = SearchQuerySet().filter(book=book.id).filter(
                    SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
                )
                if len(message) == 1 and len(contacts) > 0:
                    index = ascii_lowercase.index(message.lower())
                    contact = contacts[index].object
                    cache.delete(cache_key)
                    return log_contact(contact, user)
                cache.delete(cache_key)
                return create_message(
                    "Sorry, I didn't understand that.",
                    to=cache_key, sender=co_number,
                )
            if flow_state.startswith('find'):
                name = ':'.join(flow_state.split(':')[1:])
                contacts = SearchQuerySet().filter(book=book.id).filter(
                    SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
                )
                if len(message) == 1 and len(contacts) > 0:
                    index = ascii_lowercase.index(message.lower())
                    contact = contacts[index].object
                    cache.delete(cache_key)
                    return create_message(
                        get_contact_string(contact), to=cache_key, sender=co_number,
                    )
                cache.delete(cache_key)
                return create_message(
                    "Sorry, I didn't understand that.",
                    to=cache_key, sender=co_number,
                )


        tokens = message.split(' ')
        if len(tokens) < 2:
            return help_message()

        search_start = time.time()
        if tokens[0].lower() in MET_PREFIXES:
            if tokens[1].lower() == 'with':
                del tokens[1]
            name = ' '.join(tokens[1:])
            contacts = SearchQuerySet().filter(book=book.id).filter(
                SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
            )
            if len(contacts) > 1:
                cache.set(cache_key, "log:{}".format(name), CACHE_TIMEOUT)
                response_string = "Which {} did you mean?\n".format(name)
                response_string += get_string_from_search_contacts(contacts)
                response_string += "(DONE to exit)"
                return create_message(
                    response_string, to=cache_key, sender=co_number,
                )
            if len(contacts) == 1:
                contact = contacts[0].object
            else:
                contact = Contact.objects.create(
                    book=book,
                    name=name,
                )

            cache.delete(cache_key)
            return log_contact(contact, user)

        if tokens[0].lower() == 'find':
            name = ' '.join(tokens[1:])
            contacts = SearchQuerySet().filter(book=book.id).filter(
                SQ(name=AutoQuery(name)) | SQ(content=AutoQuery(name))
            )
            if len(contacts) == 0:
                return create_message(
                    "Hmm... I didn't find any contacts.",
                    to=cache_key, sender=co_number,
                )
            if len(contacts) == 1:
                return create_message(
                    get_contact_string(contacts[0].object),
                    to=cache_key, sender=co_number,
                )
            response_string = get_string_from_search_contacts(contacts)
            if len(contacts) > 3:
                response_string += "More: https://{}/search/?q={}".format(
                    Site.objects.get_current().domain,
                    name,
                )
            cache.set(cache_key, "find:{}".format(name), CACHE_TIMEOUT)
            return create_message(
                "Here's what I found for {}:\n{}".format(name, response_string),
                to=cache_key, sender=co_number,
            )
        return help_message()

Example 48

Project: Observatory
Source File: projects.py
View license
@login_required
def modify(request, project_url_path, tab_id = 1):
  # redirect if the url path is not in the correct format
  resp = force_url_paths(modify, project_url_path)
  if resp: return resp
  
  project = get_object_or_404(Project, url_path = project_url_path)
  screenshots = Screenshot.objects.filter(project = project)
  
  # if someone tries to edit a project they shouldn't be able to
  if not (request.user in project.authors.all() or request.user.info.mentor):
    return HttpResponseRedirect(reverse(show, args = (project.url_path,)))
  
  # default forms
  project_form = ProjectForm(instance = project)
  cloned_repo_form = ClonedRepositoryForm(instance = project.repository)
  feed_repo_form = FeedRepositoryForm(instance = project.repository)
  blog_form = BlogForm(instance = project.blog)
  screenshot_form = UploadScreenshotForm()
  
  # if changes should be saved or rejected
  if request.POST:
    # uploading a screenshot
    if 'screenshot_upload' in request.POST:
      form = UploadScreenshotForm(request.POST, request.FILES)
      if form.is_valid():
        Screenshot.create(form, request.FILES["file"], project)
      else:
        screenshot_form = form

    # wrote a post with the js overlay
    if 'title' in request.POST and 'markdown' in request.POST:
      from dashboard.views.blogs import create_post_real
      return create_post_real(request.POST)

    # editing the project's information
    elif 'title' in request.POST:
      form = ProjectForm(request.POST)
      
      # if the form is valid, save
      if form.is_valid():
        project.title = form.cleaned_data['title']
        project.website = form.cleaned_data['website']
        project.wiki = form.cleaned_data['wiki']
        project.description = form.cleaned_data['description']
        project.active = form.cleaned_data['active']
        project.save()
        project_form = ProjectForm(instance = project)
      
      # otherwise, display the errors
      else:
        project_form = form
    
    # editing a cloned repository
    elif 'clone_url' in request.POST:
      form = ClonedRepositoryForm(request.POST)
      
      if form.is_valid():
        project.repository.web_url = form.cleaned_data['web_url']
        project.repository.clone_url = form.cleaned_data['clone_url']
        project.repository.vcs = form.cleaned_data['vcs']
        project.repository.from_feed = False
        project.repository.save()
        cloned_repo_form = ClonedRepositoryForm(instance = project.repository)
      else:
        cloned_repo_form = form
    
    # editing a feed repository
    elif 'repo_rss' in request.POST:
      form = FeedRepositoryForm(request.POST)
      
      if form.is_valid():
        project.repository.repo_rss = form.cleaned_data['repo_rss']
        project.repository.cmd = form.cleaned_data['cmd']
        project.repository.web_url = form.cleaned_data['web_url']
        project.repository.from_feed = True
        project.repository.save()
        feed_repo_form = FeedRepositoryForm(instance = project.repository)
      else:
        feed_repo_form = form
    
    # editing a feed-based blog
    elif 'url' in request.POST:
      form = BlogForm(request.POST)
      
      if form.is_valid():
        project.blog.url = form.cleaned_data['url']
        project.blog.rss = form.cleaned_data['rss']
        project.blog.from_feed = True
        project.blog.save()
        blog_form = BlogForm(instance = project.blog)
      else:
        blog_form = form
    
    # switching to hosted blog
    elif 'switch-to-hosted' in request.POST:
      project.blog.from_feed = False
      project.blog.save()
      
  return render_to_response('projects/modify.html', {
    'project': project,
    'screenshots': screenshots,
    'project_form': project_form,
    'cloned_repo_form': cloned_repo_form,
    'feed_repo_form': feed_repo_form,
    'blog_form': blog_form,
    'screenshot_form': screenshot_form,
    'post_form': BlogPostForm(),
    'repo': project.repository,
    'tab': int(tab_id)
  }, context_instance = RequestContext(request))

Example 49

Project: classic.rhizome.org
Source File: views.py
View license
@login_required
def edit_profile(request): 
    context = RequestContext(request)
    rhizomeuser = request.user.get_profile()
    
    initial_list_data = [l.listid for l in Member.objects.filter(user=rhizomeuser, deleted = 0)]
    
    personal_info_form = EditPersonalInfoForm(instance=rhizomeuser)
    account_info_form = EditAccountInfoForm(instance=rhizomeuser)
    bio_form = EditBioForm(instance=rhizomeuser)
    add_info_form = EditAdditionalInfoForm(instance=rhizomeuser)
   
    try:
        address = rhizomeuser.address('billing')
        address_form = UserBillingAddressForm(instance=address)
    except:
        address_form = UserBillingAddressForm()
    
    set_password_form = SetPasswordForm(rhizomeuser)
    manage_email_form = ManageForm(request.POST or None, initial={'mailinglists':initial_list_data})
    ip_address = request.META.get('REMOTE_ADDR', 'unknown')
    updated = ''
    
    if request.method == 'POST': 
        response = ''           
        if request.POST['form'] == "personal_info":
            
            personal_info_form = EditPersonalInfoForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            
            if personal_info_form.is_valid():
                rhizomeuser = personal_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "address_form":
            try:
                address_form = UserBillingAddressForm(request.POST or None, instance=address)        
            except:
                address_form = UserBillingAddressForm(request.POST or None)
            if address_form.is_valid():
                address_form.save(rhizomeuser)
                updated = "pass"
            else:
                updated = "fail" 
                          
        if request.POST['form'] == "bio":
            bio_form = EditBioForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))        
            if bio_form.is_valid():
                rhizomeuser = bio_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                
        if request.POST['form'] == "account_info":
            account_info_form = EditAccountInfoForm(request.POST or None, request.FILES or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            if account_info_form.is_valid():
                rhizomeuser = account_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                        
        if request.POST['form'] == "set_password":
            set_password_form = SetPasswordForm(rhizomeuser,request.POST)
            if set_password_form.is_valid():
                rhizomeuser = set_password_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
                       
        if request.POST['form'] == "add_info":
            add_info_form = EditAdditionalInfoForm(request.POST or None, 
                    instance=rhizomeuser and RhizomeUser.objects.get(id=rhizomeuser.id))
            if add_info_form.is_valid():
                rhizomeuser = add_info_form.save()
                rhizomeuser.save()
                updated = "pass"
            else:
                updated = "fail" 
        
        if request.POST['form'] == "manage_email_form":   
            manage_email_form = ManageForm(request.POST)     
            if manage_email_form.is_valid():
                mailinglists = manage_email_form.cleaned_data['mailinglists']
                notice = manage_email_form.save(request, mailinglists)
                updated = "pass"
            else:
                updated = "fail"
        if updated == 'pass':
            moderator.process(rhizomeuser, request)
            return HttpResponseRedirect('/profiles/edit?updated=True')
    
    breadcrumb = (("Profiles", rhizomeuser.get_absolute_url()), ("Edit",None)) 
 
    if rhizomeuser.id == request.user.id:
        return render_to_response(
            "accounts/edit.html",
            {
            "rhizomeuser":rhizomeuser,
            "personal_info_form":personal_info_form,
            "account_info_form":account_info_form,
            "bio_form":bio_form,
            "add_info_form":add_info_form,
            "set_password_form":set_password_form,
            "manage_email_form":manage_email_form,
            "address_form":address_form,
            "updated": updated,
            "breadcrumb":breadcrumb,
            "today": datetime.datetime.now(),
            }, 
            context
            )
    else:
        return HttpResponseRedirect(reverse(profiles_list))

Example 50

Project: AutoO_with_django
Source File: views.py
View license
def server(request):
  if 'loginToken' in request.session:
    pass
  else:
    return HttpResponseRedirect('/')

  if 'page' in request.GET and request.GET['page'].isdigit():
    page_get = int(float(request.GET['page']))
  else:
    page_get = 1
  if 'query' in request.GET:
    if request.session['query'].has_key('op'):
      request.session['query'] = {'op':'True'}
      if 'pid' in request.POST:
        if request.POST['pid'] == "":
          try:
            request.session['query_data'].pop('pid')
          except:
            quit
        else:
          request.session['query_data']['pid'] = request.POST['pid']
      if 'ip' in request.POST:
        if request.POST['ip'] == "":
          try:
            request.session['query_data'].pop('ip__contains')
          except:
            a = 1
        else:
          request.session['query_data']['ip__contains'] = request.POST['ip']
      if 'srv' in request.POST:
        if request.POST['srv'] == "":
          try:
            request.session['query_data'].pop('srv')
          except:
            a = 1
        else:
          request.session['query_data']['srv'] = request.POST['srv']
      if 'status' in request.POST:
        if request.POST['status'] == "":
          try:
            request.session['query_data'].pop('status')
          except:
            a = 1
        else:
          request.session['query_data']['status'] = request.POST['status']
      exper = request.session['query_data']
    else:
      request.session['query'] = {'op':'true'}          
      if 'pid' in request.POST and request.POST['pid'] != "":
        request.session['query_data']['pid'] = request.POST['pid']
      if 'ip' in request.POST and request.POST['ip'] != "":
        request.session['query_data']['ip__contains'] = request.POST['ip']
      if 'srv' in request.POST and request.POST['srv'] != "":
        request.session['query_data']['srv'] = request.POST['srv']
      if 'status' in request.POST and request.POST['status'] != "":
        request.session['query_data']['status'] = request.POST['status']
      exper = request.session['query_data']
    
    servers = Server.objects.filter(**exper)
  else:
    request.session['query'] = {}
    request.session['query_data'] = {}
    servers = Server.objects.select_related().all()
  pagin = Paginator(servers,20)
  page_max = pagin.num_pages
  if page_get > page_max:
    page = page_max
  else:
    page = page_get
  data_list = pagin.page(page)
  if 'query' in request.GET:
    url_fp = "?query&page=1"
    if page <= 1:
      url_pp = "?query&page=1"
    else:
      url_pp = "?query&page=" + str((page - 1))
    if page >= page_max:
      url_np = "?query&page=" + str(page_max)
    else:
      url_np = "?query&page=" + str((page + 1))
    url_lp = "?query&page=" + str(page_max)
  else:
    url_fp = "?page=1"
    if page <= 1:
      url_pp = "?page=1"
    else:
      url_pp = "?page=" + str((page - 1))
    if page >= page_max:
      url_np = "?page=" + str(page_max)
    else:
      url_np = "?page=" + str((page + 1))
    url_lp = "?page=" + str(page_max)
  projects = Project.objects.all()
  rsp = render(request, 'user_assets.html', locals())
  return HttpResponse(rsp)