Showing posts with label django. Show all posts
Showing posts with label django. Show all posts

Saturday, October 27, 2012

Following relationships 'backwards'

Django lets you easily follow a ForiegnKey relationship backwards from an instance of the the referenced model back to the model containing the FK field.

The docs explain this well..

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the "Retrieving objects" section above.

Example:
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.
# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains='Lennon')
>>> b.entry_set.count()

The docs also go on to explain how and why these relations are possible..

Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don't Repeat Yourself) principle, so Django only requires you to define the relationship on one end.
The first time any model is loaded, Django iterates over every model in INSTALLED_APPS and creates the backward relationships in memory as needed. Essentially, one of the functions of INSTALLED_APPS is to tell Django the entire model domain.


Ref: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

Friday, October 26, 2012

Two Foreign Keys to same model require related_name definition

When creating a new model that requires two foreign keys to refer to the same other model, django requires you to define the related_name attribute for the ForeignKey field.

The related_name attribute specifies the name of the reverse relation from the User model back to your model.
If you don't specify a related_name, Django automatically creates one using the name of your model and the suffix _set.

Thus unless you specify a unique related_name for at least one of your FKs, your models won't validate throwing an error:
Accessor for field 'primary' clashes with related field '<FKModelname>.<modelname_set>'

 Ref: http://stackoverflow.com/questions/2642613/what-is-the-related-name-mean-in-django/2642645#2642645

Wednesday, October 10, 2012

How to fix django runserver 'port already in use' error

This usually happens if you  $ python manage.py runserver 8000 and then don't stop the server by hitting Cntrl+C but hit something like Cntrl+Z instead.

To stop the server on port 8000 so that you can run another instance again you can do the following..

Run the below command to list all your processes with 'manage' in their name.
$ ps aux | grep -i manage

Note the process_id (pid)  for our "manage.py runserver" process which should be the second column from the left.

And then simply run
$ kill -9 <pid>

e.g. $ kill -9 30144

Ref: http://stackoverflow.com/a/5788609/1415352

Tuesday, September 25, 2012

Avoid Cascading-deletes in Django-Admin

If you try deleting an object referenced by a Foreign Key or OneToOneField in Django Admin, it will attempt to do a cascade delete on all the related objects. This is documented here.

To avoid this, you need to set null = True and on_delete=models.SET_NULL as attributes for the Foreign Key like so:
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)

Ref: http://stackoverflow.com/a/6963556/1415352

Friday, September 14, 2012

Using jQuery ajax in Django requires {{csrf_token}}

Any data that is sent to a django view/api-function via POST (or even an ajax call for that matter) )will not be accepted and will return an HTTP-500 error unless a csrf-token is also sent with the request. (Just like how we do it when creating a <form> in django).

A quick fix for this is to simply supply the {{ csrf_token }} via the .ajaxSetup() function like so:
$.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});

And then follow with your .post or .ajax function..

Ref: http://stackoverflow.com/a/7715325/1415352

Wednesday, September 12, 2012

Use get_request() instead of passing request every time

So it turns out you can simply use gadjo's get_request() to acquire the request objects instead of passing it along as parameters in your functions.

Now whenever you are in any function, and you need the request object, you can simply do..


from gadjo.requestprovider.signals import get_request

and inside your function..

def thisfunctionneedsrequest():
  <variable-name> = get_request()
  ...
  user = <variable-name>.user

So you don't need to keep passing the request object down to functions anymore. This makes things much easier.

Friday, August 31, 2012

Modifying Dictionary in Django Session Does Not Modify Session

I think this is worth knowing because I spent quite a long time trying to debug a related issue.

This is the original post from SO. Read the whole thing. Very useful.

In short,

Whenever editing a session object, it is also required to explicitly say that the object was modified. This can be achieved like so:
request.session['xyz'] = 'xyz'
request.session.modfied = True
or in the settings we set,
SESSION_SAVE_EVERY_REQUEST True 
 .

Thursday, August 16, 2012

Whenever creating a new folder/module put a blank __init__.py in it

Whenever creating a new folder/module put a blank __init__.py in it. This is required if you want to import from this module into another file.

Wednesday, August 1, 2012

Tuesday, July 17, 2012

While running manage.py syncdb if "settings.DATABASES is improperly configured"

While running manage.py syncdb if "settings.DATABASES is improperly configured" although you are in the directory containing the settings.py file.

try: $ python manage.py syncdb --settings=settings

Wednesday, June 13, 2012

Setting up Eclipse Debug configs to work with Django


  • Eclipse > File > Import > General > Existing projects into workspace > Next > 
  • For 'Select root directory:' browse to the app folder. [the one with manage.py] and hit Finish.
  • We now need to install PyDev,
    Help > Install New Software > Add...
    Name: Pydev    Location: http://pydev.org/updates  >> OK
    Select only PyDev and not PyDev Mylyn... >> Next > Next > I accept > Finish > Trust all certificates > Restart Eclipse when prompted.
  • Eclipse > Debug Configurations > Python run.
  • Right click on Python Run > New.
  • Click the New_configuration which is newly created in the left pane.
  • For Project, Browse to the 'app' folder. [the one with manage.py]
  • For Main Module, Browse to the 'manage.py' inside the above app folder.
  • Then click the Arguments tab at the top.
    Add 'runserver 8000 --noreload' (without quotes) into Program arguments.
  • Hit Apply. You're done.


NOTE: You may also have to select the appropriate Interpreter after selecting Arguments. Use /path/to/venv/projectname/bin/python if inside a venv else use usr/src/bin/python2.7

Gadjo / request-provider

More often than not gadjo does not install using easy_install or pip as easily as the rest of the requirements from requirements.txt.

Best fix..

Download the requestprovider folder from here. or here http://pypi.bearstech.com/django-contrib-requestprovider/
Navigate to the "gadgjo" folder.
Paste the gadjo folder into local/lib/python2.7/site-packages  [This was for a virtualenv]
Paste the gadjo folder into usr/lib/python2.7/dist-packages [without virtualenv]

Done.

Popular Posts