Re: simplifying double decorators?
On Sun, 30 Nov 2014 10:30:29 -0800 Richard Brockie 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+unsubscr...@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. signature.asc Description: PGP signature
Re: LIMIT 21 on primary key lookups
On Sun, 14 Sep 2014 17:48:18 +0100 Ben Collier wrote: > So why 21, precisely? Because its half the answer? signature.asc Description: PGP signature
Re: very light weight django task queues
On Sun, 6 Apr 2014 03:33:30 -0700 (PDT) TinyJaguar wrote: > I've been using both django-huey and celery as task queues with > varying success in other projects. > see (https://www.djangopackages.com/grids/g/workers-queues-tasks/) > > Most of the task queues are redis based. They seem to be overkill for > our current situation and add another layer of system maintenance > (i.e a redis instance) and we want/need to have a minimum of packages > on our micro instances (currently just django, postgres, nginx and a > few tiny packages) > > Our typical background tasks occur once or twice a week! and may take > about 30 minutes to a few hours to process. > What I'm looking for is a very very simple task queue that does not > use redis or any other 'external' database. Just a bunch of tables in > the current app's database would be fine. > > what would you suggest? django-extensions allows to define scripts for cron.[hourly|daily|weekly], you just have to make cron call them. But that assumes that your tasks don't have to run asap after being scheduled. - Arnold signature.asc Description: PGP signature
Re: I'm getting obsessed! Where should I put this code?
On Sun, 9 Feb 2014 02:15:46 -0800 (PST) Glyn Jackson wrote: > So far I have moved this logic around so many times, but where should > it really be happening in my Django project? Opinions very much > welcome. Thanks > > 1) product *pre_save* - this works really well but validation looks > odd here! > 2) product *model save()* - again validation looks odd here! > 3) product *model manager *- this seems bad as I'm referencing the > stock model in product manager. > 4) *views* - I end up repeating the save validation and code looks > really bad, also I have to do it again for API and normal views > 5) *tastypie recourse* - just as bad as views I think. Model! If its validation and 'save' should stop if there is none in stock, its either a pre-save-trigger or on your own save-method before calling super(...).save(). Be aware that if you subclass your product, a pre-save trigger has to get connected to all derived classes too, so it might be easier to just add it to the save-method. The advantage is clearly that the same code is used for all views. And api-resources are a view too (or a controller but lets not discuss thie here). - Arnold signature.asc Description: PGP signature
Re: Using SSL and Apache on Windows together
On Sun, 9 Feb 2014 06:48:10 -0800 François Schiettecatte wrote: > SSL is not something that is handled by Django but is further up the > stack, you should check how to implement SSL with your Windows Server. Actually its not that high (or low) on the stack. You don't configure SSL in the OS (windows in this case), you configure it on the web-server (apache in this case). And there are plenty of apache documentation for that. - Arnold signature.asc Description: PGP signature
Re: Optimizing DB query involving annotate and aggregate
On Wed, 5 Feb 2014 10:11:29 -0800 (PST) ST wrote: > Hi, > > I'm trying to optimize the run-time of getting total credit and debt > values out of our database. Ideally I'd like to formulate it as a > Django query. This is the raw SQL query I have, which produces the > right answer and is very fast (milliseconds): > > SELECT sum(tg.total) FROM > ( > SELECT sum(t.amount) AS total, t.member_id AS member_id > FROM club_transaction AS t > WHERE t.member_id IS NOT NULL > GROUP BY t.member_id > ) AS tg > WHERE tg.total < 0 > > (plus a second query for > 0) > > My Django implementation was: > > m = > Member.objects.annotate(balance=Sum('transaction__amount')) m_debt = > m.filter(balance__lt=0).aggregate(total=Sum('balance')) m_credit = > m.filter(balance__gt=0).aggregate(total=Sum('balance')) > > which looks a lot nicer, is easier to understand and maintain. > > However, it results in the following SQL query (slightly redacted): > > SELECT SUM(balance) FROM > ( > SELECT "club_member"."id" AS "id", {all the other fields}, > SUM("club_transaction"."amount") AS "balance" > FROM "club_member" > LEFT OUTER JOIN "auth_user" ON ("club_member"."user_id" = > "auth_user"."id") > LEFT OUTER JOIN "club_transaction" ON ("club_member"."id" = > "club_transaction"."member_id") > GROUP BY "club_member"."id", {all the other fields}, > "auth_user"."last_name", "auth_user"."first_name" > HAVING SUM("club_transaction"."amount") < 0 > ORDER BY "auth_user"."last_name" ASC, "auth_user"."first_name" ASC > ) subquery > > (again, plus another one for > 0) > which is very slow (almost 1.5 seconds). > > How can I construct a Django query which doesn't request (and group > by) all the unnecessary other fields ? > I already tried playing around with only() and values() but never got > it to work. I did something similar a few years back. Its next to impossible with django-orm, just do it in raw sql. The django-orm can't really do any advanced group_by clauses. And you can't give them with extra(). Well, you can give them but they won't be used;-) Doing two (or three) orm-queries and then joining the data in python will actually be slower then doing it all in hand-crafted sql. So just do the sql by hand. And then optimize by having three columns, one with the SUM(amount) if amount>0, one with the SUM(amount) if amount<0 and one with the SUM(amount). Total credits, total depts and balance all in one query (if possible)... - Arnold signature.asc Description: PGP signature
Re: migrations to custom user model - complex project
Hi, On Fri, 24 Jan 2014 15:10:44 +0100 Frank Bieniek wrote: > a do have to upgrade an existing > django project, it is an openid provider with around 10k users. > In order to update to django 1.6 I do need to get rid of > the good old AUTH_PROFILE_MODULE and need to switch > to CustomUserModel, and I do not want to break existing mysql > constraints. > But I do not want to touch only a minimal set of files possible > and do not want to do a dumpdata load data mess. > There must be an elegant solution, someone else has already done > Any hints are welcome - I googled already, but have not found a > solution that does not break groups or other fks... We did something similar, we switched from djangos own user model + our profile to just using our profile extended by email and password (no username anymore and no openid (yet)). What you need to do depends on whether you can keep the ID's the same or not. We couldn't so we had to do the following: - In all models that had a foreignkey on the django-user, we added another foreignkey on the new user (with default=null). - Then we added a data-migration to fill the columns for the new user-model with the ids. - In the next migration we deactivated all triggers for the transaction, removed the constraints for the old django-user reference and added constraints for the new user-model. - Then the references to the old django-user can be removed. And once you defined your user model for django.auth, you have to write your own migration to drop the user-model tables from django.auth (because south doesn't see that table and model anymore). - We also renamed the references to the new user-model to be same as the references to the old user-model before all these migrations. So most code didn't need changing. - Of course you also have to adopt your python code for the specialties of the new user model... If you can keep the IDs the same as before, you probably don't need to add a second column for the new model reference. You can 'just' remove the constraints from each foreignkey pointing to the old user-model and replace it with a constraint pointing to the new user-model. Of course, before you do that you need a migration creating your new user-model and a data-migration to copy the user-data (most importantly the IDs!) to the new tables. Maybe that helps, - Arnold signature.asc Description: PGP signature
Re: wxMailServer: GUI tool to help you with testing Django e-mails
Hi On Thu, 19 Dec 2013 01:23:58 -0800 (PST) Michał Pasternak wrote: > I would like to announce a GUI app, written in wxPython, that I > quickly assembled yesterday mainly using some code from StackOverflow > and Google. > > The app is called wxMailServer and all it does is: it acts as a mail > server (it listens for traffic incoming at localhost port 25) and > when an e-mail is received, it displays this e-mail, highlighting URL > addresses in it and launching a web browser in case you click on any > of those addresses. An interesting idea. However, running a program that tries to open a port <1024 results on security issues on modern machines. Only system process are allowed (or should be allowed) to open ports there. Luckily enough, if your software has an option to start with listening on a different port, you can also set that port when telling django how to send emails. > E-mail sending is getting harder and harder nowadays, with my VM > unable to send e-mail because of local antivirus, and if I disable > it, I get notices from Google about being on an IP that is not > allowed to send e-mails. So, anyway, it looks harder and harder. Why > do that, then? E-mail server running on localhost, displaying > incoming e-mails should be the best tool to test if your app > generates proper e-mails. "Sending emails" for testing? There is this email-backend in django that just displays the messages on the console. Ideal for manual testing. And for automated testing (the only way to make sure you really always send emails with the wanted content) you just look at mailbox.outbox as described in django testing docs. Lastly there are several thousand valid reasons for mailservers not to accept un-authenticated email delivery from dail-ups and dynamic ranges. (These mails are largely called spam and are sent by botnets.) Have fun, Arnold PS: If you really want your local django to send mails to the outside via google, you can just do smtp-authentication with your valid google credentials... signature.asc Description: PGP signature
Re: Adding Objects to Query Set
Hi, define related names in ProjectMember: class ProjectMember(models.Model): project = models.ForeignKey(Project, related_name='members') member = models.ForeignKey(User) added_on = models.DateTimeField() The full query to get all Projects the User is either member or leader: Projects.objects.filter( Q(owner=user) | Q(members__member=user) ) Don't merge in python what you can merge in the database. One query in the database is (almost) always faster then two queries and merging in python. Have fun, Arnold Am Mon, 16 Dec 2013 09:56:27 -0800 (PST) schrieb antialiasis : > Rather than fetching > ProjectMember.objects.filter(member=request.user), you want to fetch > Project.objects.filter(projectmember_set__member=request.user). That > will get you Project objects rather than ProjectMember objects. > > On Monday, December 16, 2013 1:47:13 PM UTC, Vibhu Rishi wrote: > > > > Hi > > > > I am not able to figure this out. I want to add objects to a query > > set. > > > > I have 2 models : > > 1. Projects which is basically a list of projects. I have a field > > which defines the owner of the project. e.g. : > > > > class Project(models.Model): > > ... > > owner = models.ForeignKey(User) > > > > 2. ProjectMember - This is a table where I add any user ( other > > than owner ) if they are member of the project. > > > > class ProjectMember(models.Model): > > project = models.ForeignKey(Project) > > member = models.ForeignKey(User) > > added_on = models.DateTimeField() > > > > What I am trying to do is get a list of projects which the current > > user is either owner or member of. So, I have this in my view : > > > > def mylist(request): > > projects = Project.objects.filter(owner=request.user) > > member_of = ProjectMember.objects.filter(member = request.user) > > # Now find all projects the user is a member of and add to the > > projects list > > all_projects = projects > > for m in member_of: > > all_projects |= m.project > > return render (request, "project/projects_mine.html", > > {'projects':projects}) > > > > > > I am doing something wrong here as the line all_projects |= > > m.project is not working. I tried with a += also. > > > > How can I achieve what I am trying to do ? > > > > Vibhu > > > > -- > > Simplicity is the ultimate sophistication. - Leonardo da Vinci > > Life is really simple, but we insist on making it complicated. - > > Confucius > > > signature.asc Description: PGP signature
Re: Testing Frameworks and Practices(consensus?)
Am Wed, 11 Dec 2013 12:03:44 -0500 schrieb Thomas Murphy : > This seems like a more appropriate forum that SO for this discussion. > > I've been testing my apps with Selenium, which seems to be a popular > choice for Django, but so does unittest and some others, as well as > using coverage to check for code coverage. > > I'm curious to hear about others experience with testing frameworks, > particularly those who have moved through more than one about any best > practices experiences they've had, and what caused the choice to go > with what you're using now. We started classically without tests. Then I learned testing through the excellent tdd-django tutorial. And we started with djangos own runner (and thus unittest(2)). Unit tests with plain django+unittests, functional tests with django+selenium. As we encountered some problems with the test-systems handling of utf-8 in log- and test-messages, we looked at nose and nose2 as alternative test-runners. Currently we do use nose2 and are looking at py.test. Tests are run by developers during development and by jenkins after checkins. The jenkins runs are with coverage and are finished of by sonar checking code and results. So all the current frameworks currently in use by us: - Django ;-) - nose2 - selenium - jenkins - coverage.py - sonar 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+unsubscr...@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/20131212155007.2fdbd226%40orinoco. For more options, visit https://groups.google.com/groups/opt_out.
Re: Logging warnings inside settings.py
On Fri, 1 Nov 2013 10:11:05 -0700 Jon Dufresne wrote: > I am trying to log warnings inside settings.py. I want to log warnings > when settings (from an outside source) are not provided, but the > application can continue. Is this possible? It seems like this might > not work as logging requires settings.py in order to be configured, > but I want to log earlier than that. I don't think you want to do that. If I understand you correctly, you want a warning (or an error) if a setting is not defined. The correct place to throw that warning is when you need the setting, not when you define the setting. Using settings.py for that would be wrong because the setting might be set afterwards. Most settings.py I encounter or write have a ```try: import local_settings``` at the bottom... Have fun, Arnold signature.asc Description: PGP signature
Re: Django - How to combine queries in to one and display it in the template?
On Sun, 3 Nov 2013 18:31:42 +0530 Robin Lery wrote: > Suppose this is a model for an app Blog: > class Blog(models.Model): > And this is another model for an app Status: > class Status(models.Model): > How do I come up with something like this: > What I wan't is that, in the home page, I would like to display the > updates of all the user's activity in the latest order, > Eg: > 'User updated with new status: blah blah''User published a new > Blog''User published a new Blog' > like in many other social networking sites. And not to display them > both separately. And similarly in the user's profile, display all the > activities of that particular User. There are two (actually three) ways to get something like that: 1. Derive Blog and Status from the same concrete basemodel. Then you can get all the basemodel-instances ordered by time. Of course the publishing-time (and author and such things) would have to be fields on the basemodel or present on all derived classes. Advantage: You get the ordering and limiting done in the database. Disadvantage: A lot of joins in the database. 2. You do the ordering in the python-code in the view. Advantage: No concrete inheritance and thus no joins. Disadvantage: No sorting and limiting in the db (which is faster with that than your python-code will be). 3. ( Use a schema-free database, called NO-SQL in newer times, and connect the entries freely. ) Whether to choose 1. or 2. depends on what you do more: Do you fetch mixed lists and want them ordered? Or do you mainly fetch lists of specific types and only want the ordering in one or two places? Will the joins in database-space or the ordering in python-space hurt you more. Have fun, Arnold signature.asc Description: PGP signature
Re: Loading data from Django into RedShift - ORM vs SQL?
Am Thu, 17 Oct 2013 13:32:44 +0300 schrieb Avraham Serour : > The whole idea of having an ORM is not having ot deal with SQL > directly unless necessary. I would try to do it using the ORM first > but there's not general rule, each case should be analised > individually Actually you shouldn't decide each case individually but use the ORM by default! The ORM is tested for a lot of cases whereas your SQL is only working in your own case. And there are a lot of problems you might think are better to solve in raw SQL, but actually after thinking about it using the ORM will give you simpler code, simpler algorithms, more optimization and less runtime... At least its our experience that on 2/3 of the places where we 'needed' to do raw SQL replacing that by using the ORM actually improved everything. 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+unsubscr...@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/20131017231237.65b6b31f%40orinoco. For more options, visit https://groups.google.com/groups/opt_out.
Re: What is the best solution to deploy Django on a Windows server?
On Fri, 11 Oct 2013 08:35:06 -0700 (PDT) Augusto Destrero wrote: > A client of mine want to keep its existing Windows Server > infrastructure, so I'm forced to deploy my Django based web > application on Windows 2003/2007. > > The first question is: > > is Django production ready on Windows platform? > > The second is: > > to your knowledge, what is the best way to deploy Django on a Windows > server? Apache+mod_wsgi? IIS+Helicon Zoo ( > http://www.helicontech.com/articles/running-django-on-windows-with-performance-tests/ > )? Create a virtual machine, either with microsofts virtualization or with virtualbox. Install linux in it, deploy your app as you are used to do. Or even better, replace the clients win-only machine by a linux-server running a virtual machine for the django-stuff and another virtual machine for the clients windows-stuff. Have fun, Arnold signature.asc Description: PGP signature
Re: How to use selenium test against different browsers using LiveServerTestCase
On Thu, 26 Sep 2013 09:46:43 -0700 (PDT) Tianyi Wang wrote: > So follow the Django doc example, > https://docs.djangoproject.com/en/dev/topics/testing/overview/#django.test.LiveServerTestCase > In the example, the test only test against Firefox. How can I test > against different browsers without duplicate the example code? I would propose this: In your classes __init__ (or in the init of your mixin specially for this) check for an environment-variable or a django-setting to tell you the browser to use. With a fallback if nothing is defined. Then when you run the tests locally, you can decide which browser to use. And when run in jenkins, the browser is a matrix-variable giving you functional tests with all the defined browsers. Have fun, Arnold signature.asc Description: PGP signature
Re: Testing Permissions in URL Includes
On Fri, 13 Sep 2013 11:30:44 -0700 Lee Hinde wrote: > So, the question, is there a way to wrap url include calls in a > permission check? Wrapping a whole url-include would only work when the url-tree is rebuild for each request taking into account the requesting user. Todays technologies don't do that anymore. I would encourage you to look at django-braces and just use the PermissionRequiredMixin with your class-based-views. Have fun, Arnold signature.asc Description: PGP signature
Re: Django Periodic tasks
On Sat, 17 Aug 2013 03:36:29 +0100 Some Developer wrote: > I'm aware of django-cron and django-celery, both of which are capable > of doing what I want but I was wondering if I was just making a > fundamental design mistake and there maybe a better option that > someone here could explain. > > Basically customers pay money into their account in advance so that > they can use services that we offer. Each service is charged by the > minute and prices between services can vary wildly. I need to be able > to show our clients their current running total to the nearest hour > so that they know when they need to add extra funds to their account. > > My initial thought was that I would just have the equivalent of a > cron job running every hour that queries the database for the state > of each users application and then used that to produce an estimate > for their current billing. > > Alternately I could get rid of the hourly period task and just work > it out when a customer visits a certain page but that is likely to > lead to long load times and heavy database use. > > Any suggestions on what you would do in this situation? Calculate the value on each visit for now. Worry about the execution-time when your database actually has lots of users, payments and service-charges applied and the site does get slow to load. Then use django-debug-toolbar to see how many queries your are running to calculate the number and how long these queries take. Try to reduce the number of queries, do whatever you can in the database instead of in python. When you have reached your end of wisdom while optimizing the algorithm and the sql (or djangos use of sql through the orm), start looking into celery/cron/django-extensions. While celery _can_ do regular jobs, its not really its primary use. And probably not worth setting up celery+redis when you only want it to do cron-jobs. If you need celery for other stuff already, then use it for cron-jobs too. But otherwise its probably better to look at the cronjobs-framework of django-extensions. Have fun, Arnold signature.asc Description: PGP signature
Re: South doesn't recognize modification in ManytoMany fields
Hi, On Thu, 15 Aug 2013 03:31:08 +0530 Pradeep Kumar wrote: > I have made a model change from > standard = models.ManyToManyField(Standard) > to > standard = models.ManyToManyField(Standard, blank = True, null = True) > South schemamigration for this app doesn't recognize the change ? I don't see a difference between these two? Both say that you want to have zero or more connections from each item in your model to the items of Standard. And zero or more connections from each Standard-item to items in your model. M2M are done with an intermediate table. But why do you want to add lines in that table that have an entry to your model but no entry for 'Standard'? Its the same as if no entry in the intermediate. I think what django (and south) do is just ignore blank- and null-parameters. Have fun, Arnold signature.asc Description: PGP signature
Re: Query Set and Output
Hi, On Tue, 6 Aug 2013 20:19:01 -0700 (PDT) Muhammed TÜFEKYAPAN wrote: > def home(request): > output = Excuse.objects.order_by('?')[:1] [:1] selects all elements from the beginning up to the first and returns that list. true, its a list with only one member, but still a list. You want [0] to get the first element of the list/set that Excuse.objects.order_by returns. > template = loader.get_template('index.html') > context = {'output': output} > return render(request, 'index.html', context) > > I get output like this: [] > i just want to blabla section and how i get away from [] Have fun, Arnold signature.asc Description: PGP signature
Re: is Django useful for a basic site as well?
On Thu, 18 Jul 2013 17:45:32 -0400 Bill Freeman wrote: > Good programmers steal. Great programmers steal from the best. Find > a beautiful site and don't deviate much from his layout/CSS scheme. And some call their work a framework and make everyone use/steal it. @Alex: Start with bootstrap (http://twitter.github.io/bootstrap/) and be blown away by the ease and possibilities. And choose mezzanine for your django-based cms. Of course you still have to do the laymans work of setting up webservers and databases but there are many tools to help with that like fabric, chef, puppet... Have fun, Arnold signature.asc Description: PGP signature
Re: Every view requires authentication
On Wed, 17 Jul 2013 14:18:54 -0700 Jon Dufresne wrote: > On Wed, Jul 17, 2013 at 1:25 PM, Arnold Krille > wrote: > > > On Wed, 17 Jul 2013 11:22:36 -0700 Jon Dufresne > > wrote:The standard-way depende on your > > views: > > - If its function-based views, use the @login_required-decorator. > > - For class-based views we use the LoginRequiredMixin from > >django-braces. > This is a whitelist approach to the problem. That is, I must specify > every view that requires login. As nearly 99% of my views will require > authentication, I'd prefer to take a blacklist approach. That is, all > views are assumed to require login, unless I annotate the views to > not require a login. This avoids accidentally leaving views publicly > accessible when someone forgets the login_required decorator (or CBV > equivalent). > > I can achieve this with middleware (and maybe a decorator), but it > occurred to me that others probably already do this as well. I am > curious if there is a canonical approach or implementation that > others use for this very purpose. There was a thread a view days ago listing the blacklist-approach. Still interesting that you need authentication while not needing any authorization... Arnold signature.asc Description: PGP signature
Re: Design for storing likes/dislikes?
On Tue, 16 Jul 2013 17:29:47 -0700 (PDT) Victor Hooi wrote: > We have a list of users, who are going to like/dislike various > widgets. > > My question is regarding how to store the like/dislikes. > > Essentially, there can be three states between a user and a widget - > like, dislike, and unrated, so it's not just a straight Boolean. > > I'm thinking of just doing a M2M between user and widgets models, and > then storing an extra field on that M2M. > > I can either store a Boolean, for whether the item is liked/unliked - > and then an unrated item simply won't be exist in the table. > > Or I can store a integer (with a choice tupled defined), with say > 0=unrated, 1=like, 2 = unlike, and all possible combinations are > listed. > > We'll be doing queries to compare users, and see if their > likes/dislikes intersect. > > Are there any pros/cons of the two approaches for this given query, > or is there perhaps a more efficient way of storing this data? I would probably do this with an explicit many to many relationship. My first thought would be to use a boolean (true for like, false for unlike, not a row in the table for unrated). On second thought I would replace your integer-enum idea by using the integer for a real rating for example from -5 to 5. While at first you might just map like/unlike to 5/-5, for the future you could do rows of stars or rows of thumbs-up/-downs. Have fun, Arnold signature.asc Description: PGP signature
Re: Every view requires authentication
On Wed, 17 Jul 2013 11:22:36 -0700 Jon Dufresne wrote: > My application requires an authenticated user for every view (with > very few exceptions). Is there a standard correct way to handle this > or should I roll my own middleware? I'm probably not the first have > this requirement. The standard-way depende on your views: - If its function-based views, use the @login_required-decorator. - For class-based views we use the LoginRequiredMixin from django-braces. But since most of the time we have to check for permissions (and also check via our own customer-specific permissions) we only use our own PermissionRequiredMixin (derived from django-braces' mixin of the same name). If the user is not authenticated (thus AnonymousUser) it doesn't have any permissions too. Have fun, Arnold signature.asc Description: PGP signature
Re: url pattern correct but not working
On Thu, 21 Feb 2013 15:41:12 -0500 Bill Freeman wrote: > Not quite right either, even if it didn't have the non matched open > parenthesis after the carat, since it would match > "foo-bar--1234.html". > > Perhaps '^(?:[a-zA-Z0-9]+-)+(?P\d+).html$' > > (?:...) is a non-capturing group, if you're not familiar with it. Right, thats better. But this pattern is actually matching one non-capture-group for each - in the url? Not that this would be a problem though. I never yet had the need to regex a part of the url and then not use it as argument for the view... Have fun, Arnold signature.asc Description: PGP signature
Re: url pattern correct but not working
On Thu, 21 Feb 2013 10:46:05 -0800 (PST) Aswani Kumar wrote: > my url pattern > > [a-zA-Z0-9]-(?P\d+).html > > urls will be like > > news-in-finland-yesterday-festival-3456.html > > i want 3456 which is news id. > > the regex is correct but not working if i keep it in urls. > url('^[a-zA-Z0-9]-(?P\d+).html$', 'tempa'), Whether your pattern is correct or depends on what you want to achieve: - if you want to match a single digit or letter followed by a dash and a number uf digits for the id, then your pattern is correct. - if you want your pattern to macht the url you have given, then its not correct. You want something like this (untested): url(r'^([a-zA-Z0-9\-]+-(?P\d+).html$', 'tempa') And that only matches lower- and upper-case letters, numbers and dashes. If you want to allow any non-ascii characters you might want something different in that first parantheses. Have fun, Arnold signature.asc Description: PGP signature
Re: Form with variable fields
On Sat, 26 Jan 2013 17:38:03 -0800 (PST) sephii wrote: > Thanks for your answer. I wanted to avoid using a ManyToMany field in > my case for two reasons: > 1. The artist table has about 700'000 entries, which is really too > big to fit in a element > 2. I could create an autocomplete text widget to overcome point 1), > but the user should also be able to set a new artist that doesn't > exist yet in the database using these fields > > Feel free to let me know if you think of a solution that would > overcome these 2 issues. 1) Tell django to use a text-input or your own widget to display the artist-field. 2) Write your own widget to enter text, search via ajax and then set the artist. At least thats what we do with m2m-fields with ~20.000 entries. Have fun, Arnold signature.asc Description: PGP signature
Re: Form with variable fields
On Sat, 26 Jan 2013 11:39:20 -0800 (PST) sephii wrote: > Hey there, > > I'm trying to create a form with a "static" part (a "title" field, a > "date" field) and a variable part (these are "artist names", so > that's a single field that can be repeated multiple times, with a > minimum of 1). I first thought about the MultiValueField but it > requires several fields, and in my case I only want to use 1 field, > just like an inline with one field in the Django admin. I then tried > to go with a Formset, but I wasn't able to set it as mandatory (even > if the field is marked as mandatory, if it's left blank it's just > like the form is not filled so the validation always passes). Here's > the code I tried for the formset part: When one entry in one table/model has several assorted entries of an independent type, thats called a 1-to-n-relation. Or a OneToManyField in django. So essentially when you have a list of CDs, they all have album, title and stuff. But then you have a list of artists and each of these entries belongs to one CD while one CD can have several artist entries. OneToManyField from the artist to the CD. But one artist can be on several CDs. So actually you want to look at the ManyToManyField, because one artist can be on several CDs and several artists can be on one CD. Thats an n-to-m relation. Once you get these relations right, the django forms do the rest for you. Maybe that helps, Arnold signature.asc Description: PGP signature
Re: Generating HTML code
On Sat, 12 Jan 2013 05:43:40 -0800 (PST) Matteo Suppo wrote: > I use http://foundation.zurb.com/ or > http://twitter.github.com/bootstrap/ > > They don't generate html but they help build pages faster. And then there are jetstrap.com and boottheme.com which help creating your bootstrap theme and page. And give you html and bootstrap.css or variables.less to integrate into your project. Have fun, Arnold signature.asc Description: PGP signature
Re: How to implement pre-save operations for inlines in the admin interface?
On Fri, 16 Nov 2012 08:43:04 +1100 Mike Dewhirst wrote: > On 16/11/2012 3:52am, Arnold Krille wrote: > > Why do you want to do this only in the admin interface? > > Its a generic thing: every time you save/change a period you should > > set the end-date of the previous one. So I would do this with a > > post-save hook (aka signal) directly in the models.py. Or maybe > > even subclass your models save- operation. > > This is a question not a competing opinion. > > Why would you use a post-save signal? Why not just override save() > and use the model manager directly to find the previous period and if > it doesn't have and end date pop one in? I don't have the ultimate answer. We have a case here where we apply one function to several models, on one model on pre-save-signal and on several models on post-save-signal. We could have done the same by subclassing all these models from one abstract base which would have had one field and the save-function. The signals seemed easier to us with less clutter in the model-graph. For the case presented by Carsten, I am even more open to do it with overwriting the save-function. With the save-function you have the functionality directly where it belongs. With a post-save-signal you have maybe a bit cleaner kind of code: the save-function of the object is only the save-function of the object. The modification of a different object is in a different function that has its execution-definition written directly above. But its a matter of personal taste I think. Have fun, Arnold signature.asc Description: PGP signature
Re: How to implement pre-save operations for inlines in the admin interface?
Hi, On Thu, 15 Nov 2012 18:15:37 +0100 Carsten Fuchs wrote: > Am 15.11.2012 17:52, schrieb Arnold Krille: > > On Thursday 15 November 2012 17:12:09 Carsten Fuchs wrote: > >> [...] > >> (Note that it is not enough to consider the Period that changed -- > >> rather, it is the 'end' in *another* period (the one "before" it) > >> that must be modified and saved, too.) > >> What is the proper hook or where the best place to do this? > > Why do you want to do this only in the admin interface? > > Its a generic thing: every time you save/change a period you should > > set the end-date of the previous one. So I would do this with a > > post-save hook (aka signal) directly in the models.py. Or maybe > > even subclass your models save- operation. > Well, I realize that this would be useful also generically, outside > of the admin interface. Even if you do not need it outside the admin-interface (in this project), from the logic this belongs to the model, not into some view. > Alas, if e.g. I overrode the save() method of the Period class, is it > safe to access *another* Period instance from there? Yep, thats save. If you use a db that has transactions, both the change to the other object should be rolled back when saving of the current objects fails as it should all end up in one transaction. :-) > I don't really fully understand how the admin interface works when a > model with inlines is saved, but I suspect that the inlines are saved > in a loop. But if in an early iteration of the loop I modified > another instance that is routinely saved *again* in a later iteration > of the loop, it will be a bug. I can't really comment on the admin interfaces working as we use that only for the stuff only a superuser has rights. Everything else is edited in our frontend-code. But saving inlines in the admin interface should be the same as saving forms with formsets underneath. Have fun, Arnold signature.asc Description: PGP signature
Re: transfer one django app to another server
On Thursday 15 November 2012 21:03:56 siddharth ghumre wrote: > You can just copy your app from your local machine to server. > Just keep in mind to do the necessary changes in the settings.py file. And remember that you might have a database that (if its on the same machine but not a local sqlite) has to be ported too. > On Thu, Nov 15, 2012 at 8:24 PM, Lewis wrote: > > In order to transfer the app from local machine to another server. what > > should I do? Can I just copy everything or do I need to reinstall app that > > I install? Have fun, Arnold signature.asc Description: This is a digitally signed message part.
Re: How to implement pre-save operations for inlines in the admin interface?
On Thursday 15 November 2012 17:12:09 Carsten Fuchs wrote: > using Django 1.3 (soon 1.4), we use models like these: > class Staff(models.Model): > name = models.CharField(max_length=80) > class Period(models.Model): > staff = models.ForeignKey(Staff) > begin = models.DateField() > end = models.DateField(editable=False)# see below > # The actual data that describes this period, > # e.g. department, salary, ... > department = models.CharField(max_length=60) > class Meta: > ordering = ['begin'] > > There are normally several Period instances for each staff member, and > the set of periods for one staff member form a chronological sequence: > > A period begins at the day given in 'begin'. > It ends at the day before the *next* period begins. > > Thus, in our original design, there was no field 'end' in the Period > model, because logically, it was not needed. (The last period is > "open-ended".) > > However, we found that many queries are very difficult to build without > the 'end' (such as "Find all staff members in department X on November > 1st"), and thus are planning to add it as shown above. > > 'end' should always be computed automatically as the day before the > begin of the next period, but I don't know where this is best > implemented in the admin interface: > > class PeriodInline(admin.TabularInline): > model = Period > class StaffAdmin(admin.ModelAdmin): > inlines = [ PeriodInline ] > > (Note that it is not enough to consider the Period that changed -- > rather, it is the 'end' in *another* period (the one "before" it) that > must be modified and saved, too.) > > What is the proper hook or where the best place to do this? Why do you want to do this only in the admin interface? Its a generic thing: every time you save/change a period you should set the end-date of the previous one. So I would do this with a post-save hook (aka signal) directly in the models.py. Or maybe even subclass your models save- operation. Have fun, Arnold signature.asc Description: This is a digitally signed message part.
Re: How many developers have moved to class-based views?
On Sun, 11 Nov 2012 09:57:16 -0800 (PST) Kevin wrote: > Hello! > > I am curious of how many existing Django developers have moved over > to class-based views or are still using the function-based ones. I > tend to use a mix depending on what I am trying to do. I try to > stick with class-based views, but fallback to function-based ones for > process-based views, views which don't return a template but redirect > after processing some end-user action. Docs on CBV in django1.4 are a bit sparse to say the least. And we started the project before there where CBV. But we are using CBV for some stuff already, deriving a JqtableAjaxView from the documentations AjaxView has saved us quite some code. And simplified testing. there are other occasions where CBV would result in more code, so we don't use it there... One of our greatest problems is that you can't use permission decorators as easily as with function-views. But on one hand I just learned about the Mixins of django-braces. And on the other hand most of our views need object-based permissions with a much more sophisticated permission model than just users and groups. So we are doing a lot ourselves and only provide an auth-backend to get our permissions into the django-mechanisms where its applicable. And for example its far better to return an empty dataset via an ajax-call than a 404 or a login-page. So we actually filter the datasets on what the user is allowed to view and not disturb him with ugly error-messages... Have fun, Arnold signature.asc Description: PGP signature
Re: How to call a database function from Django?
On Thursday 08 November 2012 15:17:38 Kurtis Mullins wrote: > I usually create management commands and call that. Here's the docs: > https://docs.djangoproject.com/en/dev/howto/custom-management-commands/ As an alternative you can use django_extensions and create a job. Might be to much when its just one job. But as soon as your project gets bigger and needs several jobs with mixed intervals, its easier. Have fun, Arnold signature.asc Description: This is a digitally signed message part.