Risk of exposing an ID of entry in DRF framework - python

I'm building an API and I've started using the GenericAPIViews. In this example
class InsertActivityChange(UpdateAPIView):
authentication_classes = []
permission_classes = []
serializer_class = ActivitiesSerializer
lookup_field = 'id'
def get_queryset(self):
return Activities.objects.filter(id=self.kwargs['id'])
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
path('insertactivitychange/<int:id>', views.InsertActivityChange.as_view(), name='insertactivitychange'),
I've used a generic class to do updates for an object. My concern is if I'm risking much by allowing the ID to be directly inputted after the URL. Obviously, I'd further mitigate the risk by properly configuring the authentication and permission class, so is the ID of the entry even a security risk?

If you're worried about access, remember to add permissions and filters. If you're focused on security and hiding resources, make sure they will 404 instead of 401 or 403. Have a look at DRF filtering section and in serializers use PrimaryKeyRelatedField queryset where you filter based on user.
If you're worried about exposing pks, just use UUIDs. It will still be visible but a human can't predict what the next id is.
So even if 3rd party knows the id of a resource, it should return 404 if you want to hide a resource. That way you expose a meaningless value to the attacker.

Let me try to answer this question.
One can't ensure security just by hiding things
One of my mentor always emphasized on this line whenever I had asked similar questions.
To answer you question, according to me no you don't expose any security flaws by exposing IDs, in fact it's one of the most common way of allowing users to interact with resources over APIs.
You will be surely required to have authentication and authorisation in place to safeguard the resource manipulation by malicious sources. In context of DRF and django you can achieve this by using authentication and permissions.
Hope this answers your question.

Related

Custom authenticate method or maybe some other way to do the same? Django

this is a begginers question. I have a database in mysql with tables to store users with a username and a password, simple as that. I dont want to use the authentications backends and tables that django installs the first time you run 'SyncDb'. So my question is: how do i tell django to use the database that i created instead of looking for active Users in the pre defined databases.
I´m using this code but of course this is looking for users in the already mention 'auth_user' table.
class LoginView(FormView):
form_class = LoginForm
redirect_field_name = REDIRECT_FIELD_NAME
template_name = 'login.html'
success_url = 'index'
def form_valid(self, form):
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username,
password=password)
if user is not None:
if user.is_active:
login(self.request, user)
return HttpResponseRedirect(self.get_success_url())
else:
return self.form_invalid(form)
def form_invalid(self):
return HttpResponseRedirect(reverse('app_name:login'))
def get_success_url(self):
if self.success_url:
redirect_to = self.success_url
else:
redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')
netloc = urlparse.urlparse(redirect_to)[1]
if not redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
elif netloc and netloc != self.request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
return redirect_to
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid()
So that´s my begginers question. Thank you very much
PS: my form_invalid() is not working...(error: passing 2 parameters instead of 1) any suggestions please tell me. Again, thank you very much
We had to figure this out for our project and the initial confusion comes from the fact that you basically need to handle two issues in Django to make this happen:
1) Make sure that that app is routed to the correct database
1a) Make sure that other database can actually be written by Django
2) Create an "app" module to use to overwrite the default user model
Luckily this is pretty much straightforward once the problem is clearly defined.
https://docs.djangoproject.com/en/dev/topics/db/multi-db/
The first section "Defining your databases" will show you how to add additional databases to your project. Make sure you have credentials for Django to use to access, so depending on your access structure, that may include an additional step or not.
After that the section "Automatic database routing" will explain the general idea behind db routers. However, I recommend you check out this excellent discussion and leverage that code to make your database routing easier: http://justcramer.com/2010/12/30/database-routers-in-django/. This way you can just make your project use this router and define a lib in your settings.py (DATABASE_CONFIG) to tell each application where to route after setting DATABASE_ROUTERS to the code at the link. Make your default router the one with all the django stuff, then define your legacy db whenever necessary.
Lastly, for the user model check out the docs on "Customizing authentication in Django" (I can't post the link because this is my first answer and I do not have enough reputation). You will need to write a custom model (and potentially admin forms and custom authentication for permissions based on your implementation) and include it through your project settings.py with AUTH_USER_MODEL. The key section on that page is "Substituting a custom User model". If it is as simple as just matching a password to a user it should be mostly painless, however, be careful how your passwords are hashed. PASSWORD_HASHERS in your settings.py tells django the hashers to use on passwords when saving them (and the preferred order). If you want to keep a certain hashing scheme you need to move that to the top of the list, otherwise, Django will port it to the first listed and thus preferred scheme when it needs to do a PW access. This is actually a great feature as it will auto-migrate passwords to stronger schemes, but may be something to be mindful of if you need to integrate with other systems.
As a general pointer (and this is in no way intended as a RTM) the Django documents are very good and will typically answer your questions (and if not the source is quite readable and I've had to solve a few things that way). However, as you might notice, until you realize the issue you are trying to fix, and what Django calls it, it can be a little confusing to fit the pieces together. It will be worth your time if you plan to do anything at all with Django to get a good read of the primary documentation, possibly twice, to help make the pieces fit. Hopefully this answers your question and gives you a sense of where to go, as you can see this scenario can get a little broad so let me know if a more specific question gives you issues, otherwise these are the key points I recall implementing and during a code review as I wrote this.

Separation of business logic and data access in django

I am writing a project in Django and I see that 80% of the code is in the file models.py. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
I find it ugly that my model level (which was supposed to be
responsible only for the work with data from a database) is also
sending email, walking on API to other services, etc.
Also, I find it unacceptable to place business logic in the view, because
this way it becomes difficult to control. For example, in my
application there are at least three ways to create new
instances of User, but technically it should create them uniformly.
I do not always notice when the methods and
properties of my models become non-deterministic and when they develop
side effects.
Here is a simple example. At first, the User model was like this:
class User(db.Models):
def get_present_name(self):
return self.name or 'Anonymous'
def activate(self):
self.status = 'activated'
self.save()
Over time, it turned into this:
class User(db.Models):
def get_present_name(self):
# property became non-deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
def activate(self):
# method now has a side effect (send message to user)
self.status = 'activated'
self.save()
send_mail('Your account is activated!', '…', [self.email])
What I want is to separate entities in my code:
Database level entities, i.e. database level logic: What kind of data does my application store?
application level entities, i.e. business level logic: What does my application do?
What are the good practices to implement such an approach that can be applied in Django?
It seems like you are asking about the difference between the data model and the domain model – the latter is where you can find the business logic and entities as perceived by your end user, the former is where you actually store your data.
Furthermore, I've interpreted the 3rd part of your question as: how to notice failure to keep these models separate.
These are two very different concepts and it's always hard to keep them separate. However, there are some common patterns and tools that can be used for this purpose.
About the Domain Model
The first thing you need to recognize is that your domain model is not really about data; it is about actions and questions such as "activate this user", "deactivate this user", "which users are currently activated?", and "what is this user's name?". In classical terms: it's about queries and commands.
Thinking in Commands
Let's start by looking at the commands in your example: "activate this user" and "deactivate this user". The nice thing about commands is that they can easily be expressed by small given-when-then scenario's:
given an inactive user
when the admin activates this user
then the user becomes active
and a confirmation e-mail is sent to the user
and an entry is added to the system log
(etc. etc.)
Such scenario's are useful to see how different parts of your infrastructure can be affected by a single command – in this case your database (some kind of 'active' flag), your mail server, your system log, etc.
Such scenario's also really help you in setting up a Test Driven Development environment.
And finally, thinking in commands really helps you create a task-oriented application. Your users will appreciate this :-)
Expressing Commands
Django provides two easy ways of expressing commands; they are both valid options and it is not unusual to mix the two approaches.
The service layer
The service module has already been described by #Hedde. Here you define a separate module and each command is represented as a function.
services.py
def activate_user(user_id):
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
Using forms
The other way is to use a Django Form for each command. I prefer this approach, because it combines multiple closely related aspects:
execution of the command (what does it do?)
validation of the command parameters (can it do this?)
presentation of the command (how can I do this?)
forms.py
class ActivateUserForm(forms.Form):
user_id = IntegerField(widget = UsernameSelectWidget, verbose_name="Select a user to activate")
# the username select widget is not a standard Django widget, I just made it up
def clean_user_id(self):
user_id = self.cleaned_data['user_id']
if User.objects.get(pk=user_id).active:
raise ValidationError("This user cannot be activated")
# you can also check authorizations etc.
return user_id
def execute(self):
"""
This is not a standard method in the forms API; it is intended to replace the
'extract-data-from-form-in-view-and-do-stuff' pattern by a more testable pattern.
"""
user_id = self.cleaned_data['user_id']
user = User.objects.get(pk=user_id)
# set active flag
user.active = True
user.save()
# mail user
send_mail(...)
# etc etc
Thinking in Queries
You example did not contain any queries, so I took the liberty of making up a few useful queries. I prefer to use the term "question", but queries is the classical terminology. Interesting queries are: "What is the name of this user?", "Can this user log in?", "Show me a list of deactivated users", and "What is the geographical distribution of deactivated users?"
Before embarking on answering these queries, you should always ask yourself this question, is this:
a presentational query just for my templates, and/or
a business logic query tied to executing my commands, and/or
a reporting query.
Presentational queries are merely made to improve the user interface. The answers to business logic queries directly affect the execution of your commands. Reporting queries are merely for analytical purposes and have looser time constraints. These categories are not mutually exclusive.
The other question is: "do I have complete control over the answers?" For example, when querying the user's name (in this context) we do not have any control over the outcome, because we rely on an external API.
Making Queries
The most basic query in Django is the use of the Manager object:
User.objects.filter(active=True)
Of course, this only works if the data is actually represented in your data model. This is not always the case. In those cases, you can consider the options below.
Custom tags and filters
The first alternative is useful for queries that are merely presentational: custom tags and template filters.
template.html
<h1>Welcome, {{ user|friendly_name }}</h1>
template_tags.py
#register.filter
def friendly_name(user):
return remote_api.get_cached_name(user.id)
Query methods
If your query is not merely presentational, you could add queries to your services.py (if you are using that), or introduce a queries.py module:
queries.py
def inactive_users():
return User.objects.filter(active=False)
def users_called_publysher():
for user in User.objects.all():
if remote_api.get_cached_name(user.id) == "publysher":
yield user
Proxy models
Proxy models are very useful in the context of business logic and reporting. You basically define an enhanced subset of your model. You can override a Manager’s base QuerySet by overriding the Manager.get_queryset() method.
models.py
class InactiveUserManager(models.Manager):
def get_queryset(self):
query_set = super(InactiveUserManager, self).get_queryset()
return query_set.filter(active=False)
class InactiveUser(User):
"""
>>> for user in InactiveUser.objects.all():
… assert user.active is False
"""
objects = InactiveUserManager()
class Meta:
proxy = True
Query models
For queries that are inherently complex, but are executed quite often, there is the possibility of query models. A query model is a form of denormalization where relevant data for a single query is stored in a separate model. The trick of course is to keep the denormalized model in sync with the primary model. Query models can only be used if changes are entirely under your control.
models.py
class InactiveUserDistribution(models.Model):
country = CharField(max_length=200)
inactive_user_count = IntegerField(default=0)
The first option is to update these models in your commands. This is very useful if these models are only changed by one or two commands.
forms.py
class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
A better option would be to use custom signals. These signals are of course emitted by your commands. Signals have the advantage that you can keep multiple query models in sync with your original model. Furthermore, signal processing can be offloaded to background tasks, using Celery or similar frameworks.
signals.py
user_activated = Signal(providing_args = ['user'])
user_deactivated = Signal(providing_args = ['user'])
forms.py
class ActivateUserForm(forms.Form):
# see above
def execute(self):
# see above
user_activated.send_robust(sender=self, user=user)
models.py
class InactiveUserDistribution(models.Model):
# see above
#receiver(user_activated)
def on_user_activated(sender, **kwargs):
user = kwargs['user']
query_model = InactiveUserDistribution.objects.get_or_create(country=user.country)
query_model.inactive_user_count -= 1
query_model.save()
Keeping it clean
When using this approach, it becomes ridiculously easy to determine if your code stays clean. Just follow these guidelines:
Does my model contain methods that do more than managing database state? You should extract a command.
Does my model contain properties that do not map to database fields? You should extract a query.
Does my model reference infrastructure that is not my database (such as mail)? You should extract a command.
The same goes for views (because views often suffer from the same problem).
Does my view actively manage database models? You should extract a command.
Some References
Django documentation: proxy models
Django documentation: signals
Architecture: Domain Driven Design
I usually implement a service layer in between views and models. This acts like your project's API and gives you a good helicopter view of what is going on. I inherited this practice from a colleague of mine that uses this layering technique a lot with Java projects (JSF), e.g:
models.py
class Book:
author = models.ForeignKey(User)
title = models.CharField(max_length=125)
class Meta:
app_label = "library"
services.py
from library.models import Book
def get_books(limit=None, **filters):
""" simple service function for retrieving books can be widely extended """
return Book.objects.filter(**filters)[:limit] # list[:None] will return the entire list
views.py
from library.services import get_books
class BookListView(ListView):
""" simple view, e.g. implement a _build and _apply filters function """
queryset = get_books()
Mind you, I usually take models, views and services to module level and
separate even further depending on the project's size
First of all, Don't repeat yourself.
Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the zen of python from time to time.
Take a look at active projects
more people = more need to organize properly
the django repository they have a straightforward structure.
the pip repository they have a straigtforward directory structure.
the fabric repository is also a good one to look at.
you can place all your models under yourapp/models/logicalgroup.py
e.g User, Group and related models can go under yourapp/models/users.py
e.g Poll, Question, Answer ... could go under yourapp/models/polls.py
load what you need in __all__ inside of yourapp/models/__init__.py
More about MVC
model is your data
this includes your actual data
this also includes your session / cookie / cache / fs / index data
user interacts with controller to manipulate the model
this could be an API, or a view that saves/updates your data
this can be tuned with request.GET / request.POST ...etc
think paging or filtering too.
the data updates the view
the templates take the data and format it accordingly
APIs even w/o templates are part of the view; e.g. tastypie or piston
this should also account for the middleware.
Take advantage of middleware / templatetags
If you need some work to be done for each request, middleware is one way to go.
e.g. adding timestamps
e.g. updating metrics about page hits
e.g. populating a cache
If you have snippets of code that always reoccur for formatting objects, templatetags are good.
e.g. active tab / url breadcrumbs
Take advantage of model managers
creating User can go in a UserManager(models.Manager).
gory details for instances should go on the models.Model.
gory details for queryset could go in a models.Manager.
you might want to create a User one at a time, so you may think that it should live on the model itself, but when creating the object, you probably don't have all the details:
Example:
class UserManager(models.Manager):
def create_user(self, username, ...):
# plain create
def create_superuser(self, username, ...):
# may set is_superuser field.
def activate(self, username):
# may use save() and send_mail()
def activate_in_bulk(self, queryset):
# may use queryset.update() instead of save()
# may use send_mass_mail() instead of send_mail()
Make use of forms where possible
A lot of boilerplate code can be eliminated if you have forms that map to a model. The ModelForm documentation is pretty good. Separating code for forms from model code can be good if you have a lot of customization (or sometimes avoid cyclic import errors for more advanced uses).
Use management commands when possible
e.g. yourapp/management/commands/createsuperuser.py
e.g. yourapp/management/commands/activateinbulk.py
if you have business logic, you can separate it out
django.contrib.auth uses backends, just like db has a backend...etc.
add a setting for your business logic (e.g. AUTHENTICATION_BACKENDS)
you could use django.contrib.auth.backends.RemoteUserBackend
you could use yourapp.backends.remote_api.RemoteUserBackend
you could use yourapp.backends.memcached.RemoteUserBackend
delegate the difficult business logic to the backend
make sure to set the expectation right on the input/output.
changing business logic is as simple as changing a setting :)
backend example:
class User(db.Models):
def get_present_name(self):
# property became not deterministic in terms of database
# data is taken from another service by api
return remote_api.request_user_name(self.uid) or 'Anonymous'
could become:
class User(db.Models):
def get_present_name(self):
for backend in get_backends():
try:
return backend.get_present_name(self)
except: # make pylint happy.
pass
return None
more about design patterns
there's already a good question about design patterns
a very good video about practical design patterns
django's backends are obvious use of delegation design pattern.
more about interface boundaries
Is the code you want to use really part of the models? -> yourapp.models
Is the code part of business logic? -> yourapp.vendor
Is the code part of generic tools / libs? -> yourapp.libs
Is the code part of business logic libs? -> yourapp.libs.vendor or yourapp.vendor.libs
Here is a good one: can you test your code independently?
yes, good :)
no, you may have an interface problem
when there is clear separation, unittest should be a breeze with the use of mocking
Is the separation logical?
yes, good :)
no, you may have trouble testing those logical concepts separately.
Do you think you will need to refactor when you get 10x more code?
yes, no good, no bueno, refactor could be a lot of work
no, that's just awesome!
In short, you could have
yourapp/core/backends.py
yourapp/core/models/__init__.py
yourapp/core/models/users.py
yourapp/core/models/questions.py
yourapp/core/backends.py
yourapp/core/forms.py
yourapp/core/handlers.py
yourapp/core/management/commands/__init__.py
yourapp/core/management/commands/closepolls.py
yourapp/core/management/commands/removeduplicates.py
yourapp/core/middleware.py
yourapp/core/signals.py
yourapp/core/templatetags/__init__.py
yourapp/core/templatetags/polls_extras.py
yourapp/core/views/__init__.py
yourapp/core/views/users.py
yourapp/core/views/questions.py
yourapp/core/signals.py
yourapp/lib/utils.py
yourapp/lib/textanalysis.py
yourapp/lib/ratings.py
yourapp/vendor/backends.py
yourapp/vendor/morebusinesslogic.py
yourapp/vendor/handlers.py
yourapp/vendor/middleware.py
yourapp/vendor/signals.py
yourapp/tests/test_polls.py
yourapp/tests/test_questions.py
yourapp/tests/test_duplicates.py
yourapp/tests/test_ratings.py
or anything else that helps you; finding the interfaces you need and the boundaries will help you.
Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".
In Django, a "model" is not merely a database abstraction. In some respects, it shares duty with the Django's "view" as the controller of MVC. It holds the entirety of behavior associated with an instance. If that instance needs to interact with an external API as part of it's behavior, then that's still model code. In fact, models aren't required to interact with the database at all, so you could conceivable have models that entirely exist as an interactive layer to an external API. It's a much more free concept of a "model".
In Django, MVC structure is as Chris Pratt said, different from classical MVC model used in other frameworks, I think the main reason for doing this is avoiding a too strict application structure, like happens in others MVC frameworks like CakePHP.
In Django, MVC was implemented in the following way:
View layer is splitted in two. The views should be used only to manage HTTP requests, they are called and respond to them. Views communicate with the rest of your application (forms, modelforms, custom classes, of in simple cases directly with models).
To create the interface we use Templates. Templates are string-like to Django, it maps a context into them, and this context was communicated to the view by the application (when view asks).
Model layer gives encapsulation, abstraction, validation, intelligence and makes your data object-oriented (they say someday DBMS will also). This doesn't means that you should make huge models.py files (in fact a very good advice is to split your models in different files, put them into a folder called 'models', make an '__init__.py' file into this folder where you import all your models and finally use the attribute 'app_label' of models.Model class). Model should abstract you from operating with data, it will make your application simpler. You should also, if required, create external classes, like "tools" for your models.You can also use heritage in models, setting the 'abstract' attribute of your model's Meta class to 'True'.
Where is the rest? Well, small web applications generally are a sort of an interface to data, in some small program cases using views to query or insert data would be enough. More common cases will use Forms or ModelForms, which are actually "controllers". This is not other than a practical solution to a common problem, and a very fast one. It's what a website use to do.
If Forms are not enogh for you, then you should create your own classes to do the magic, a very good example of this is admin application: you can read ModelAmin code, this actually works as a controller. There is not a standard structure, I suggest you to examine existing Django apps, it depends on each case. This is what Django developers intended, you can add xml parser class, an API connector class, add Celery for performing tasks, twisted for a reactor-based application, use only the ORM, make a web service, modify the admin application and more... It's your responsability to make good quality code, respect MVC philosophy or not, make it module based and creating your own abstraction layers. It's very flexible.
My advice: read as much code as you can, there are lots of django applications around, but don't take them so seriously. Each case is different, patterns and theory helps, but not always, this is an imprecise cience, django just provide you good tools that you can use to aliviate some pains (like admin interface, web form validation, i18n, observer pattern implementation, all the previously mentioned and others), but good designs come from experienced designers.
PS.: use 'User' class from auth application (from standard django), you can make for example user profiles, or at least read its code, it will be useful for your case.
An old question, but I'd like to offer my solution anyway. It's based on acceptance that model objects too require some additional functionality while it's awkward to place it within the models.py. Heavy business logic may be written separately depending on personal taste, but I at least like the model to do everything related to itself. This solution also supports those who like to have all the logic placed within models themselves.
As such, I devised a hack that allows me to separate logic from model definitions and still get all the hinting from my IDE.
The advantages should be obvious, but this lists a few that I have observed:
DB definitions remain just that - no logic "garbage" attached
Model-related logic is all placed neatly in one place
All the services (forms, REST, views) have a single access point to logic
Best of all: I did not have to rewrite any code once I realised that my models.py became too cluttered and had to separate the logic away. The separation is smooth and iterative: I could do a function at a time or entire class or the entire models.py.
I have been using this with Python 3.4 and greater and Django 1.8 and greater.
app/models.py
....
from app.logic.user import UserLogic
class User(models.Model, UserLogic):
field1 = models.AnyField(....)
... field definitions ...
app/logic/user.py
if False:
# This allows the IDE to know about the User model and its member fields
from main.models import User
class UserLogic(object):
def logic_function(self: 'User'):
... code with hinting working normally ...
The only thing I can't figure out is how to make my IDE (PyCharm in this case) recognise that UserLogic is actually User model. But since this is obviously a hack, I'm quite happy to accept the little nuisance of always specifying type for self parameter.
I would have to agree with you. There are a lot of possibilities in django but best place to start is reviewing Django's design philosophy.
Calling an API from a model property would not be ideal, it seems like it would make more sense to do something like this in the view and possibly create a service layer to keep things dry. If the call to the API is non-blocking and the call is an expensive one, sending the request to a service worker (a worker that consumes from a queue) might make sense.
As per Django's design philosophy models encapsulate every aspect of an "object". So all business logic related to that object should live there:
Include all relevant domain logic
Models should encapsulate every aspect of an “object,” following Martin Fowler’s Active Record design pattern.
The side effects you describe are apparent, the logic here could be better broken down into Querysets and managers. Here is an example:
models.py
import datetime
from djongo import models
from django.db.models.query import QuerySet
from django.contrib import admin
from django.db import transaction
class MyUser(models.Model):
present_name = models.TextField(null=False, blank=True)
status = models.TextField(null=False, blank=True)
last_active = models.DateTimeField(auto_now=True, editable=False)
# As mentioned you could put this in a template tag to pull it
# from cache there. Depending on how it is used, it could be
# retrieved from within the admin view or from a custom view
# if that is the only place you will use it.
#def get_present_name(self):
# # property became non-deterministic in terms of database
# # data is taken from another service by api
# return remote_api.request_user_name(self.uid) or 'Anonymous'
# Moved to admin as an action
# def activate(self):
# # method now has a side effect (send message to user)
# self.status = 'activated'
# self.save()
# # send email via email service
# #send_mail('Your account is activated!', '…', [self.email])
class Meta:
ordering = ['-id'] # Needed for DRF pagination
def __unicode__(self):
return '{}'.format(self.pk)
class MyUserRegistrationQuerySet(QuerySet):
def for_inactive_users(self):
new_date = datetime.datetime.now() - datetime.timedelta(days=3*365) # 3 Years ago
return self.filter(last_active__lte=new_date.year)
def by_user_id(self, user_ids):
return self.filter(id__in=user_ids)
class MyUserRegistrationManager(models.Manager):
def get_query_set(self):
return MyUserRegistrationQuerySet(self.model, using=self._db)
def with_no_activity(self):
return self.get_query_set().for_inactive_users()
admin.py
# Then in model admin
class MyUserRegistrationAdmin(admin.ModelAdmin):
actions = (
'send_welcome_emails',
)
def send_activate_emails(self, request, queryset):
rows_affected = 0
for obj in queryset:
with transaction.commit_on_success():
# send_email('welcome_email', request, obj) # send email via email service
obj.status = 'activated'
obj.save()
rows_affected += 1
self.message_user(request, 'sent %d' % rows_affected)
admin.site.register(MyUser, MyUserRegistrationAdmin)
I'm mostly agree with chosen answer (https://stackoverflow.com/a/12857584/871392), but want to add option in Making Queries section.
One can define QuerySet classes for models for make filter queries and so on. After that you can proxy this queryset class for model's manager, like build-in Manager and QuerySet classes do.
Although, if you had to query several data models to get one domain model, it seems more reasonable to me to put this in separate module like suggested before.
Most comprehensive article on the different options with pros and cons:
Idea #1: Fat Models
Idea #2: Putting Business Logic in Views/Forms
Idea #3: Services
Idea #4: QuerySets/Managers
Conclusion
Source:
https://sunscrapers.com/blog/where-to-put-business-logic-django/

How can I make Django-Tastypie override a resource if it already exists?

I'm working with some simple django-tastypie Resources with the following problem:
Imagine I'm building a simple rating system. I have a resource, call it Rating that has both a User and a Comment. Each user has at most one rating per comment.
I'd like to make a generic resource that takes a tuple ('user', 'comment'). Then, whenever I do a POST with a new Rating, I'd like it to check the user and comment fields to see if a rating matching both of those fields already exists. If it does, overwrite the existing resource, otherwise create a new resource (so that any API call will always pass Django's unique_together).
I'm working with obj_get as a starting point, but having difficulty understanding how to properly override it to get this behavior.
Following the discussion on IRC in #tastypie:
It's recommended not to alter standard API behavior, as this can be dangerous in the sense that the clients will not see consistent behavior across the API.
One solution is to let Tastypie return a 4xx response when trying to create the Rating, and in this case the client would PATCH the existing rating.
If, however, the performance boost is really necessary, you should only alter the behavior if the client formally asks for this. Which in your case would mean adding a replace_existing_rating=True parameter to the POST request.
So in your case, if you did decide you need the performance boost, you could:
class CommentResource(ModelResource):
def obj_create(self, bundle, request=None, **kwargs):
if bundle.data.get("replace_existing_rating", False):
try:
bundle.obj = self._meta.object_class._default_manager.get(**conditions)
except self._meta.object_class.DoesNotExist:
bundle.obj = self._meta.object_class()

Multiple versions of django admin page for the same model

In my django admin section, I'd like to show different versions of the admin page depending on what kind of user is currently logged in. I can think of a couple ways this might work, but haven't figured out how to do any of them.
Perhaps I could put logic into the admin.ModelAdmin to look at the current user and change the 'exclude' field dynamically. Does that work? Or maybe run different custom templates based on who's logged in, and have the templates include / exclude the fields as appropriate.
I could register two versions of the admin.ModelAdmin class, one for each type of user, and maybe restrict access through permissions? But the permissions system seems to believe fairly deeply in one set of permissions per model class so I'm not sure how to change that.
I could grab a couple of the widgets that are used in rendering the admin page templates, and include them in my own page that does the one specific job I need powerful users to be able to do.
I could set up multiple AdminSites and restrict access to them through the url / view system. But then I'm not sure how to register different admin.ModelAdmin classes with the different AdminSites.
Any advice on this would be appreciated.
Answer
Thanks for the hint. Here's how I did it...
def get_form(self, request, obj=None, **kwargs):
"""This dynamically inserts the "owners" field into the exclude list
if the current user is not superuser.
"""
if not request.user.is_superuser:
if self.exclude:
self.exclude.append('owners')
else:
self.exclude = ['owners']
else:
# Necessary since Admin objects outlive requests
try:
self.exclude.remove('owners')
except:
pass
return super(OwnersModelAdmin,self).get_form(request, obj=None, **kwargs)
There are quite a few hooks provided in the ModelAdmin class for this sort of thing.
One possibility would be to override the get_form method. This takes the request, as well as the object being edited, so you could get the current user from there, and return different ModelForms dependent on the user.
It's worth looking at the source for ModelAdmin - it's in django.contrib.admin.options - to see if overriding this or any other other methods might meet your needs.

Django Project structure, recommended structure to share an extended auth "User" model across apps?

I'm wondering what the common project/application structure is when the user model extended/sub-classed and this Resulting User model is shared and used across multiple apps.
I'd like to reference the same user model in multiple apps.
I haven't built the login interface yet, so I'm not sure how it should fit together.
The following comes to mind:
project.loginapp.app1
project.loginapp.app2
Is there a common pattern for this situation?
Would login best be handled by a 'login app'?
Similar to this question but more specific.
django application configuration
UPDATE
Clarified my use-case above.
I'd like to add fields (extend or subclass?) to the existing auth user model. And then reference that model in multiple apps.
Why are you extending User? Please clarify.
If you're adding more information about the users, you don't need to roll your own user and auth system. Django's version of that is quite solid. The user management is located in django.contrib.auth.
If you need to customize the information stored with users, first define a model such as
class Profile(models.Model):
...
user = models.ForeignKey("django.contrib.auth.models.User", unique=True)
and then set
AUTH_PROFILE_MODULE = "appname.profile"
in your settings.py
The advantage of setting this allows you to use code like this in your views:
def my_view(request):
profile = request.user.get_profile()
etc...
If you're trying to provide more ways for users to authenticate, you can add an auth backend. Extend or re-implement django.contrib.auth.backends.ModelBackend and set it as
your AUTHENTICATION_BACKENDS in settings.py.
If you want to make use of a different permissions or groups concept than is provided by django, there's nothing that will stop you. Django makes use of those two concepts only in django.contrib.admin (That I know of), and you are free to use some other concept for those topics as you see fit.
You should check first if the contrib.auth module satisfies your needs, so you don't have to reinvent the wheel:
http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth
edit:
Check this snippet that creates a UserProfile after the creation of a new User.
def create_user_profile_handler(sender, instance, created, **kwargs):
if not created: return
user_profile = UserProfile.objects.create(user=instance)
user_profile.save()
post_save.connect(create_user_profile_handler, sender=User)
i think the 'project/app' names are badly chosen. it's more like 'site/module'. an app can be very useful without having views, for example.
check the 2008 DjangoCon talks on YouTube, especially the one about reusable apps, it will make you think totally different about how to structure your project.

Categories