tags:

views:

22

answers:

2

I have a .sql database with which i interact using Django . The database in the beginning is filled with public data that can be accessed from anynone. Multiple individual users can add rows into a table(private data). How can a user see only the changes he made in the database(private data)?

A: 

I'm assuming that users have to log into this application. If yes, add a column to every table for the username. Add WHERE username = ? to every query so they can see only their data.

For data manipulation requests, make sure that the username matches the value for every row; forbid the operation if not true.

duffymo
+2  A: 

I assume you're using django.contrib.auth. You just need to do something like:

from django.contrib.auth.models import User

# ...

class PrivateData(models.Model):
    # ... private data fields ...
    user = models.ForeignKey(User)

Then you can get just that user's fields with:

PrivateData.objects.filter(user=request.user)

EDIT: So, if your users are just IP addresses, and you're not using a login mechanism, you don't really need django.contrib.auth... though it's good to have anyway since you can use it to authenticate yourself and use the built-in admin stuff to manage your site.

If you just want to tie data to IP addresses, set up an IPUser model:

class IPUser(models.Model):
    address = models.CharField(max_length=64, unique=True) # Big enough for IPv6
    # Add whatever other discrete (not list) data you want to store with this address.

class PrivateData(models.Model):
    # ... private data fields ...
    user = models.ForeignKey(IPUser)

The view function looks something like:

def the_view(request):
    remoteAddr = request.META['REMOTE_ADDR']
    try:
        theUser = IPUser.objects.get(address=remoteAddr)
    except IPUser.DoesNotExist:
        theUser = IPUser.objects.create(address=remoteAddr)
    userModifiedData = PrivateData.objects.filter(user=theUser)

One thing to note: when you're testing this with manage.py runserver, you'll need to specify the IP address via environment variable:

$ REMOTE_ADDR=127.0.0.1 manage.py runserver

When you use Django with a real web server like Apache, the server will set the variable for you.

There are probably several ways to optimize this, but this should get you started.

Mike DeSimone
Thanks!I haven't read so much about contrib.auth but if i guess you have to set different user names in order to distinguish them but the only things that can distinguish my users is their ip
Display Name