Sunday, November 30, 2014

Re: simplifying double decorators?

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.22 (GNU/Linux)

iF4EAREIAAYFAlR7dIMACgkQtuvagsE+DE4L5AD8DeWestttJMMoeLx7J7RkquWn
fmAi1sCpirsZUJHmFsYBAKhh7MvCkRIzZhy0cykmBHwXgVSusDrlnKZu2iaCut/W
=kO9Y
-----END PGP SIGNATURE-----
On Sun, 30 Nov 2014 10:30:29 -0800 Richard Brockie
<richard@ontheday.net> wrote:
> I'm running into the situation where I have several views with the
> same set of decorators:
> @login_required()
> @user_passes_test(some_test_function, login_url='/',
> redirect_field_name=None)
> def some_view(request):
> # some code
> return render(request, 'some_template.html', locals())
>
> How would I go about combining the two (or more) decorators into a
> single decorator that can be used instead and retain the
> functionality?

Well, if the user has to pass a test, you have to have a user first.
And unless the AnonymousUser passes your permissions tests, the
combination of "@login_required" and "@user_passes_test" is a
redundancy… At least it was in my old project I worked for where we
replaced these duplicates and used only the permissions tests and it
worked great. No user -> no permissions to check for. (Actually it was
no user -> no company & no roles -> no permissions.)

Have fun,

Arnold

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20141130204816.48a79081%40xingu.arnoldarts.de.
For more options, visit https://groups.google.com/d/optout.

Re: simplifying double decorators?

Hi,

def my_double_decorator(view):
    view
= user_passes_test(some_test_function, login_url='/', redirect_field_name=None)(view)
   
return login_required()(view)

Collin


On Sunday, November 30, 2014 1:31:12 PM UTC-5, Richard Brockie wrote:
Hi,

I'm running into the situation where I have several views with the same set of decorators:

@login_required()
@user_passes_test(some_test_function, login_url='/', redirect_field_name=None)
def some_view(request):
    # some code
    return render(request, 'some_template.html', locals())

How would I go about combining the two (or more) decorators into a single decorator that can be used instead and retain the functionality?

IE: this:

@login_required()
@user_passes_test(some_test_function, login_url='/', redirect_field_name=None)
def some_view...

becomes abstracted to something like this:

@my_custom_decorator_with_redirects()
def some_view...


--
    R.

Richard Brockie

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b67a07f2-6a18-46a8-a418-05afc23e73f3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: how add path to open()

Hi,

I think you want something like this. (Just make sure a login name doesn't have '..' in it :).

filehandler = open('users/' + login, "wb")

Collin


On Saturday, November 29, 2014 2:35:31 PM UTC-5, Dariusz Mysior wrote:

I join to topic with my problem

I want to create new file with login and password in new file and I can do it with code below, but I don't know how save this new files in one folder users

def rejestracja(login, haslo): save=None login_tmp=login haslo_tmp=haslo save={login_tmp:haslo_tmp}

 filehandler
=open(login,"wb")
pickle
.dump(save,filehandler)
filehandler
.close()
filehandler
=open(login,"rb")
file
=pickle.load(filehandler)
filehandler
.close()
print file
raw_input
("\n\nWcisnij [ENTER]: ")

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b22c4e9d-a796-427d-8557-c7fcf6bba9cd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Problem with queryset filtering with Django’s new Prefetch option

Hi,

Try this:

chapters = Chapter.objects.filter(course=course).prefetch_related(
        Prefetch('status_chapter', queryset=LessonStatus.objects.filter(student=request.user).select_related('lesson')),
)

Otherwise, maybe the to_attr will help.

Collin



On Saturday, November 29, 2014 8:21:03 AM UTC-5, Tobias Abdon wrote:
I am trying to use prefetch_related's new Prefetch option to further filter a database query. Using debug toolbar I can see that prefetch_related is doing its job in making only three DB queries. However, I am positive that the queryset filter I'm passing in is not working. Even though I'm using the option, all of the records are being retrieved in the query.

The goal of the below code is to show a list of Chapters. For each chapter, show its lessons. For each lesson, show the logged in user's status (complete/incomplete).

Models
class Chapter(models.Model):
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)
    name = models.CharField(max_length=100)
    slug = AutoSlugField(populate_from='name')
    desc = models.TextField()

class Lesson(models.Model):
    name = models.CharField(max_length=100)
    chapter = models.ForeignKey(Chapter, related_name='les_chapter')

class LessonStatus(models.Model):
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)
    lesson = models.ForeignKey(Lesson, related_name="status_lesson")
    student = models.ForeignKey(User)
    chapter = models.ForeignKey(Chapter, related_name="status_chapter")


View
def chapter_list(request, course_slug):

    course = Course.objects.get(slug=course_slug)

    chapters = Chapter.objects.filter(course=course).prefetch_related(
        Prefetch('status_chapter__lesson__chapter', queryset=LessonStatus.objects.filter(student=request.user)),
    )

    return TemplateResponse(request,
        'course/chapter_list_parent.html',
        {'chapters': chapters, 'course': course,}
    )


Template
<div id="chapters">
    {% for ch in chapters %}
        <p>{{ ch.name }}</p>
        {% for le in ch.status_chapter.all %}
            <p>lesson status: {{ le.status }}</p>
            <p>lesson name: {{ le.lesson.name }}</p>
        {% endfor %}
    {% endfor %}
</div>

When I run this code the LessonStatus is not being filtered by student=request.user. Instead, it is simply getting all LessonStatus records, including those that are for other users. 

Can anyone see if there's something wrong with the above code? Or any ideas how to troubleshoot? There are no errors generated.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b77fa7c2-c2ef-4570-a0ce-717836832fa1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Constructing query

Hi,

This might work:

Tag.objects.filter(name__startswith='A').exclude(company=None).order_by('name').all()

Collin


On Friday, November 28, 2014 9:08:42 AM UTC-5, termopro wrote:
I have 2 models:
Companies and Tags.

A company may have several tags associated with it, so Tag contains many-to-many relation to Company.

If i'd like to get Tags starting with "A" i'd write:
tags = Tag.objects.filter(name__startswith='A').order_by('name').all()

But how do i get the list of tags (beginning with letter 'A') which are associated with at least 1 company ?

In sql it would be something like:

SELECT * FROM
tag
WHERE
name LIKE 'A%' AND id IN (SELECT tag_id FROM tag_organization)


?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b660f738-b3d7-4cc5-babc-3e47ff7d3542%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Test client to a redirect requiring a login doesn't set redirect_chain properly? [2nd follow-up]

Hi,

As of django 1.7, the admin will redirect to a separate login page (whatever url reverse('admin:login') returns).

https://github.com/django/django/commit/be0ad62994a340ad54a0b328771931932a45a899

You could use a middleware to do an earlier, more straightforward require login.

Collin


On Friday, November 28, 2014 7:46:05 AM UTC-5, Tim Chase wrote:
On 2014-11-27 20:32, Tim Chase wrote:
> As a bit of follow-up information, if I use runserver and browse to
> the view, it redirects me to /admin/common/region/add/ but it
> displays as the login screen.  Am I missing why this wouldn't do a
> redirect to my named login URL?

A careful reading of [1] suggests that the admin provides its own
login page via the login_template setting: "Path to a custom template
that will be used by the admin site login view."  It apparently
renders this at the URL of the destination page rather than
redirecting to the regular (contrib.auth or some named auth-URL) and
providing a "next={{original_url}}"

Is there any way to get the admin to just use the contrib.auth login
page that I already have in place?

-tkc

[1]
https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.AdminSite.login_template



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0e38f463-efd7-4ee7-9715-0ca42cdc6477%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: PDF not saving on Django using open()

Hi,

merger.write("document-output.pdf")
response
.write(merger)
return response

This might work:

merger.write(response)
return response

Though, it would be more memory efficient to write it to a temporary file and then either redirect to that url or stream out the temporary file.

Collin


On Friday, November 28, 2014 5:06:14 AM UTC-5, George Rogers wrote:

trying to save files on static after pdfcrowd provides the file. I've tried adding the path to be specific it doesn't work.

from PyPDF2 import PdfFileMerger, PdfFileReader  from django.template import RequestContext  from django.shortcuts import render_to_response, get_object_or_404    import pdfcrowd  from django.http import HttpResponse  from wildling.models import *  from django.shortcuts import redirect    def home(request, template_name='brochures_form.html'):      context = RequestContext(request)      if request.method == 'POST':          context['name'] = name = request.POST.get('name','')          context['adults'] = adults = request.POST.get('adult','')          context['children'] = children = request.POST.get('child','')          context['infant'] = infant = request.POST.get('infant','')          context['start_date'] = start_date = request.POST.get('start-date','')          context['end_date'] = end_date = request.POST.get('end_date','')          context['country'] = country = request.POST.get('country','')          context['destination'] = destination = request.POST.get('destination','')          context['price'] = price = request.POST.get('price','')          context['background_photo'] = background_photo = request.POST.get('background-photo','')          context['from_user'] = from_user = request.POST.get('from','')          context['iteniary'] = iteniary = request.POST.get('iteniary','')          context['days'] = days = request.POST.get('days','')          context['destination'] = destination = request.POST.get('destination','')          context['property_name'] = property_name = request.POST.get('property','')          context['content'] = content = request.POST.get('content','')          context['iteniary'] = iteniary = request.POST.get('iteniary','')            #destinations and countries background photo created by not set          brochure = Brochures(name=name, ref_id="xxx", adults=adults, children=children, infant=infant,                      price=price, content=content, iteneary=iteniary)          brochure.save()            request.session['br_id'] = brochure.id          return redirect('http://wilderness.maasaimara.com/generate/')        return render_to_response(template_name, context, )        def generate_pdf(request, br_id, num):      context = RequestContext(request)      list_of_pages = ["http://127.0.0.1:8000/page"+x+"/" for x in list("123456")]      pdfs = ["page"+x+".pdf" for x in list("123456")]      merger = PdfFileMerger()      client = pdfcrowd.Client("samuel254", "86e62657536d264e8217478d56abd72e")      br_id = response.session["br_id"]      brochure = Brochures.objects.get(br_id)        # set HTTP response headers      response = HttpResponse(mimetype="application/pdf")      response["Cache-Control"] = "max-age=0"      response["Accept-Ranges"] = "none"      response["Content-Disposition"] = "attachment; filename=document-output.pdf"        for num in list("123456"):          path = "/home/samuel/Documents/Documents/wilderness/wilderness/static/pdf/"          html = "http://wilderness.maasaimara.com/{1}/page{0}/".format(num,br_id)          pdf = "page{0}.pdf".format(num)          pdf_file = client.convertURI(html)          local = open(pdf,'w')          local.write(pdf_file)          local.close()          merger.append(open(pdf, 'r+b'))        merger.write("document-output.pdf")      response.write(merger)      return response

The urls.py

from django.conf import settings  from django.conf.urls import patterns, include, url  from django.conf.urls.static import static  from django.views.generic import TemplateView    from django.contrib import admin  from views import generate_pdf,home    urlpatterns = patterns("",      url(r"^$", home, name="home"),      url(r"^(?P<br_id>d{4})/page(?P<num>[0-9]+)/", generate_pdf),        url(r"^admin/", include(admin.site.urls)),      url(r"^account/", include("account.urls")),  )    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I need to confirm where the file is going, it's not crashing and returns the document-output.pdf but it's blank.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/63d0ed70-89f9-4c56-992c-f5f59d6269ba%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.