Search Results

Search found 3789 results on 152 pages for 'django contrib'.

Page 15/152 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Writing good tests for Django applications

    - by Ludwik Trammer
    I've never written any tests in my life, but I'd like to start writing tests for my Django projects. I've read some articles about tests and decided to try to write some tests for an extremely simple Django app or a start. The app has two views (a list view, and a detail view) and a model with four fields: class News(models.Model): title = models.CharField(max_length=250) content = models.TextField() pub_date = models.DateTimeField(default=datetime.datetime.now) slug = models.SlugField(unique=True) I would like to show you my tests.py file and ask: Does it make sense? Am I even testing for the right things? Are there best practices I'm not following, and you could point me to? my tests.py (it contains 11 tests): # -*- coding: utf-8 -*- from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse import datetime from someproject.myapp.models import News class viewTest(TestCase): def setUp(self): self.test_title = u'Test title: bareksc' self.test_content = u'This is a content 156' self.test_slug = u'test-title-bareksc' self.test_pub_date = datetime.datetime.today() self.test_item = News.objects.create( title=self.test_title, content=self.test_content, slug=self.test_slug, pub_date=self.test_pub_date, ) client = Client() self.response_detail = client.get(self.test_item.get_absolute_url()) self.response_index = client.get(reverse('the-list-view')) def test_detail_status_code(self): """ HTTP status code for the detail view """ self.failUnlessEqual(self.response_detail.status_code, 200) def test_list_status_code(self): """ HTTP status code for the list view """ self.failUnlessEqual(self.response_index.status_code, 200) def test_list_numer_of_items(self): self.failUnlessEqual(len(self.response_index.context['object_list']), 1) def test_detail_title(self): self.failUnlessEqual(self.response_detail.context['object'].title, self.test_title) def test_list_title(self): self.failUnlessEqual(self.response_index.context['object_list'][0].title, self.test_title) def test_detail_content(self): self.failUnlessEqual(self.response_detail.context['object'].content, self.test_content) def test_list_content(self): self.failUnlessEqual(self.response_index.context['object_list'][0].content, self.test_content) def test_detail_slug(self): self.failUnlessEqual(self.response_detail.context['object'].slug, self.test_slug) def test_list_slug(self): self.failUnlessEqual(self.response_index.context['object_list'][0].slug, self.test_slug) def test_detail_template(self): self.assertContains(self.response_detail, self.test_title) self.assertContains(self.response_detail, self.test_content) def test_list_template(self): self.assertContains(self.response_index, self.test_title)

    Read the article

  • Problem with anchor tags in Django after using lighttpd + fastcgi

    - by Drew A
    I just started using lighttpd and fastcgi for my django site, but I've noticed my anchor links are no longer working. I used the anchor links for sorting links on the page, for example I use an anchor to sort links by the number of points (or votes) they have received. For example: the code in the html template: ... {% load sorting_tags %} ... {% ifequal sort_order "points" %} {% trans "total points" %} {% trans "or" %} {% anchor "date" "date posted" %} {% order_by_votes links request.direction %} {% else %} {% anchor "points" "total points" %} {% trans "or" %} {% trans "date posted" %} ... The anchor link on "www.mysite.com/my_app/" for total points will be directed to "my_app/?sort=points" But the correct URL should be "www.mysite.com/my_app/?sort=points" All my other links work, the problem is specific to anchor links. The {% anchor %} tag is taken from django-sorting, the code can be found at http://github.com/directeur/django-sorting Specifically in django-sorting/templatetags/sorting_tags.py Thanks in advance.

    Read the article

  • csrf error in django

    - by niklasfi
    Hello, I want to realize a login for my site. I basically copied and pasted the following bits from the Django Book together. However I still get an error (CSRF verification failed. Request aborted.), when submitting my registration form. Can somebody tell my what raised this error and how to fix it? Here is my code: views.py: # Create your views here. from django import forms from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.shortcuts import render_to_response def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/books/") else: form = UserCreationForm() return render_to_response("registration/register.html", { 'form': form, }) register.html: <html> <body> {% block title %}Create an account{% endblock %} {% block content %} <h1>Create an account</h1> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Create the account"> </form> {% endblock %} </body> </html>

    Read the article

  • Django URL Conf Returns Incorrect "Current URL"

    - by natnit
    I have a django app that is mostly done, and the URLs work perfectly when I run it with the manage.py runserver command. However, I've recently tried to get it running via lighttpd, and many links have stopped working. For example: http://mysite.com/races/32 should work, but instead throws this error message. Page not found (404) Request Method: GET Request URL: http://mysite.com/races/32 Using the URLconf defined in racetrack.urls, Django tried these URL patterns, in this order: ^admin/ ^create/$ ^races/$ ^races/(?P<race_id>\d+)/$ ^races/(?P<race_id>\d+)/manage/$ ^races/(?P<text>\w+)/$ ^user/(?P<kol_id>\d+)/$ ^$ ^login/$ ^logout/$ The current URL, 32, didn't match any of these. The request URL is accurate, but the last line (which displays the current URL) is giving 32 instead of races/32 as expected. Here is my urlconf: from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('racetrack.races.views', (r'^admin/', include(admin.site.urls)), (r'^create/$', 'create'), (r'^races/$', 'index'), (r'^races/(?P<race_id>\d+)/$', 'detail'), (r'^races/(?P<race_id>\d+)/manage/$', 'manage'), (r'^races/(?P<text>\w+)/$', 'index'), (r'^user/(?P<kol_id>\d+)/$', 'user'), # temporary for index page replace with welcome page (r'^$', 'index'), ) urlpatterns += patterns('django.contrib.auth.views', (r'^login/$', 'login', {'template_name': 'races/login.html'}), (r'^logout/$', 'logout', {'next_page': '/'}), ) Thank you.

    Read the article

  • Doing a count over a filter query efficiently in django

    - by apple_pie
    Hello, Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's much more efficient to do the count without retrieving those rows like so "SELECT COUNT(*) FROM ...". Is there a way to do so in django?

    Read the article

  • customizing Django look and feel in Python

    - by user248237
    I am learning Django and got it to work with wsgi. I'm following the tutorial here: http://docs.djangoproject.com/en/1.1/intro/tutorial01/ My question is: how can I customize the look and feel of Django? Is there a repository of templates that "look good", kind of like there are for Wordpress, that I can start from? I find the tutorial counterintuitive in that it goes immediately toward customizing the admin page of Django, rather than the main pages visible to users of the site. Is there an example of a "typical" Django site, with a decent template, that I can look at and built on/modify? The polls application is again not very representative since it's so specialized. any references on this would be greatly appreciated. thanks.

    Read the article

  • Can django's auth_user.username be varchar(75)? How could that be done?

    - by perrierism
    Is there anything wrong with running alter table on auth_user to make username be varchar(75) so it can fit an email? What does that break if anything? If you were to change auth_user.username to be varchar(75) where would you need to modify django? Is it simply a matter of changing 30 to 75 in the source code?: username = models.CharField(_('username'), max_length=30, unique=True, help_text=_("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters")) Or is there other validation on this field that would have to be changed or any other repercussions to doing so? See comment discussion with bartek below regarding the reason for doing it.

    Read the article

  • Adding links to full change forms for inline items in django admin?

    - by David Eyk
    I have a standard admin change form for an object, with the usual StackedInline forms for a ForeignKey relationship. I would like to be able to link each inline item to its corresponding full-sized change form, as the inline item has inlined items of its own, and I can't nest them. I've tried everything from custom widgets to custom templates, and can't make anything work. So far, the "solutions" I've seen in the form of snippets just plain don't seem to work for inlines. I'm getting ready to try some DOM hacking with jQuery just to get it working and move on. I hope I must be missing something very simple, as this seems like such a simple task! Using Django 1.2.

    Read the article

  • How can I call model methods or properties from Django Admin?

    - by kg
    Is there a natural way to display model methods or properties in the Django admin site? In my case I have base statistics for a character that are part of the model, but other things such as status effects which affect the total calculation for that statistic: class Character(models.Model): base_dexterity = models.IntegerField(default=0) @property def dexterity(stat_name): total = self.base_dexterity total += sum(s.dexterity for s in self.status.all()]) return total It would be nice if I could display the total calculated statistic alongside the field to change the base statistic in the Change Character admin page, but it is not clear to me how to incorporate that information into the page.

    Read the article

  • Django 1.5 custom User model error. "Manager isn't available; User has been swapped"

    - by bpetit
    I extend the django user model as described in the dev doc. I wan't to keep most of the original User model features so I extend the AbstractUser class. I've defined in settings.py: AUTH_USER_MODEL = 'myapp.CustomUser' My user class: class CustomUser(AbstractUser): custom_field = models.ForeignKey('OtherModel') objects = UserManager() Everything seems to work fine but when I try to make it managed by the admin site: admin.site.register(CustomUser, UserAdmin) I get this error on the admin CustomUser creation page (after validation of the password confirmation form): AttributeError: Manager isn't available; User has been swapped for 'myapp.CustomUser' The point is that I need this model managed by the admin site in order to have the same creation process as with the original User model (two step process with password validation). Thanks for any reply

    Read the article

  • Specifying default value for django hidden form field - bone DRY?

    - by jMyles
    So let's say at the last minute (in the view) I decide I want to specify a default for a field and make it hidden, like so: form.fields['coconut'] = forms.ModelChoiceField(label="", widget=forms.HiddenInput(), queryset=swallow.coconuts.all(), initial=some_particular_coconut) My question is this: Do I really need to specify queryset here? I mean, I already know, from initial, exactly which coconut I'm talking about. Why do I also need to specify that the universe of available coconuts is the set of coconuts which this particular swallow carried (by the husk)? Is there a way I can refrain from specifying queryset? Simply omitting causes django to raise TypeError. If indeed it is required, isn't this a bit damp?

    Read the article

  • 500 Internal Server Error when setting up Apache on Ubuntu+Django

    - by ApacheQ
    I tried with Apache on ubuntu 9.04 and get the same error: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, webmaster@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. And my apache/error.log is: [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] ServerName: 'sapint2' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] DocumentRoot: '/etc/apache2/htdocs' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] URI: '/' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Location: '/' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Directory: None [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Filename: '/etc/apache2/htdocs' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] PathInfo: '/' [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] Traceback (most recent call last): [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch\n default=default_handler, arg=req, silent=hlist.silent) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1229, in _process_target\n result = _execute_target(config, req, object, arg) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1128, in _execute_target\n result = object(arg) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/modpython.py", line 180, in handler\n return ModPythonHandler()(req) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/modpython.py", line 142, in call\n self.load_middleware() [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 45, in load_middleware\n mod = import_module(mw_module) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module\n import(name) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/middleware.py", line 4, in \n from django.utils.cache import patch_vary_headers [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/utils/cache.py", line 25, in \n from django.core.cache import get_cache [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/cache/init.py", line 187, in \n cache = get_cache(DEFAULT_CACHE_ALIAS) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/cache/init.py", line 179, in get_cache\n cache = backend_cls(location, params) [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] File "/usr/local/lib/python2.7/dist-packages/django/core/cache/backends/memcached.py", line 139, in init\n "Memcached cache backend requires either the 'memcache' or 'cmemcache' library" [Sat Oct 06 09:32:04 2012] [error] [client 10.0.64.10] InvalidCacheBackendError: Memcached cache backend requires either the 'memcache' or 'cmemcache' library [Sat Oct 06 09:51:30 2012] [notice] caught SIGTERM, shutting down [Sat Oct 06 09:51:31 2012] [notice] mod_python: Creating 8 session mutexes based on 150 max processes and 0 max threads. [Sat Oct 06 09:51:31 2012] [notice] mod_python: using mutex_directory /tmp [Sat Oct 06 09:51:31 2012] [notice] Apache/2.2.17 (Ubuntu) PHP/5.3.5-1ubuntu7.11 with Suhosin-Patch mod_python/3.3.1 Python/2.7.1+ mod_wsgi/3.3 configured -- resuming normal operations I need some help Thanks

    Read the article

  • Installing Django on Windows

    - by Pranav
    Ever needed to install Django in a Microsoft Windows environment, here is a quick start guide to make that happen: Read through the official Django installation documentation, it might just save you a world of hut down the road. Download Python for your version of Windows. Install Python, my preference here is to put it into the Program Files folder under a folder named Python<Version> Add your chosen Python installation path into your Windows path environment variable. This is an optional step, however it allows you to just type python in the command line and have it fire up the Python interpreter. An easy way of adding it is going into Control Panel, System and into the Environment Variables section. Download Django, you can either download a compressed file or if you’re comfortable with using version control – check it out from the Django Subversion repository. Create a folder named django under your <Python installation directory>\Lib\site-packages\ folder. Using my example above that would have been C:\Program Files\Python25\Lib\site-packages\. If you chose to download the compressed file, open it and extract the contents of the django folder into your newly created folder. If you’d prefer to check it out from Subversion, the normal check out points are http://code.djangoproject.com/svn/django/trunk/ for the latest development copy or a named release which you’ll find under http://code.djangoproject.com/svn/django/tags/releases/. Done, you now have a working Django installation on Windows. At this point, it’d be pertinent to confirm that everything is working properly, which you can do by following the first Django tutorial. The tutorial will make mention of django-admin.py, which is a utility which offers some basic functionality to get you off the ground. The file is located in the bin folder under your Django installation directory. When you need to use it, you can either type in the full path to it or simply add that file path into your environment variables as well. Hope this helps!

    Read the article

  • Django Error - AttributeError: 'Settings' object has no attribute 'LOCALE_PATHS'

    - by Randy Simon
    I am trying to learn django by following along with this tutorial. I am using django version 1.1.1 I run django-admin.py startproject mysite and it creates the files it should. Then I try to start the server by running python manage.py runserver but here is where I get the following error. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 213, in execute translation.activate('en-us') File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 73, in activate return real_activate(language) File "/Library/Python/2.6/site-packages/django/utils/translation/__init__.py", line 43, in delayed_loader return g['real_%s' % caller](*args, **kwargs) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 205, in activate _active[currentThread()] = translation(language) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 194, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/Library/Python/2.6/site-packages/django/utils/translation/trans_real.py", line 172, in _fetch for localepath in settings.LOCALE_PATHS: File "/Library/Python/2.6/site-packages/django/utils/functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'LOCALE_PATHS' Now, I can add a LOCAL_PATH atribute set to an empty string to my settings.py file but then it just complains about another setting and so on. What am I missing here?

    Read the article

  • Django + Apache wsgi = paths problem

    - by Shamanu4
    Hello. I have this view which generates interface language options menu def lang_menu(request,language): lang_choices = [] import os.path for lang in settings.LANGUAGES: if os.path.isfile("gui/%s.py" % lang) or os.path.isfile("gui/%s.pyc" % lang): langimport = "from gui.%s import menu" % lang try: exec(langimport) except ImportError: lang_choices.append({'error':'invalid language file'}) else: lang_choices.append(menu) else: lang_choices.append({'error':'lang file not found'}) t = loader.get_template('gui/blocks/lang_menu_options.html') data = '' for lang in lang_choices: if not 'error' in lang: data = "%s\n%s" % (data,t.render(Context(lang))) if not data: data = "Error! No languages configured or incorrect language files!" return Context({'content':data}) When I'am using development server (python manage.py runserver ...) it works fine. But when I ported my app to apache wsgi server I've got error "No languages configured or incorrect language files!" Here is my Apache config <VirtualHost *:9999> WSGIScriptAlias / "/usr/local/etc/django/terminal/django.wsgi" <Directory "/usr/local/etc/django/terminal"> Options +ExecCGI Allow From All </Directory> Alias /media/ "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/" <Location /media/> SetHandler None </Location> <Directory "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/> Allow from all </Directory> Alias /static/ "/usr/local/etc/django/terminal/media/" <Location /static/> SetHandler None </Location> ServerName ******* ServerAlias ******* ErrorLog /var/log/django.error.log TransferLog /var/log/django.access.log </VirtualHost> django.wsgi: import os, sys sys.path.append('/usr/local/etc/django') sys.path.append('/usr/local/etc/django/terminal') os.environ['DJANGO_SETTINGS_MODULE'] = 'terminal.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() It's look like as problem with path configuration but I'm stuck here ...

    Read the article

  • Django caching seems to be causing problems

    - by Issy
    Hey guys, i have just implemented the Django Cache Local Memory back end in some my code, however it seems to be causing a problem. I get the following error when trying to view the site (With Debug On): Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 279, in run self.result = application(self.environ, self.start_response) File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 651, in __call__ return self.application(environ, start_response) File "/usr/lib/python2.6/dist-packages/django/core/handlers/wsgi.py", line 245, in __call__ response = middleware_method(request, response) File "/usr/lib/python2.6/dist-packages/django/middleware/cache.py", line 91, in process_response patch_response_headers(response, timeout) File "/usr/lib/python2.6/dist-packages/django/utils/cache.py", line 112, in patch_response_headers response['Expires'] = http_date(time.time() + cache_timeout) TypeError: unsupported operand type(s) for +: 'float' and 'str' I have checked my code, for caching everything seems to be ok. For example, i have the following in my middleware. MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ) My settings for Cache: CACHE_BACKEND = 'locmem://' CACHE_MIDDLEWARE_SECONDS = '3600' CACHE_MIDDLEWARE_KEY_PREFIX = 'za' CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True And some of my code (template tag): def get_featured_images(): """ provides featured images """ cache_key = 'featured_images' images = cache.get(cache_key) if images is None: images = FeaturedImage.objects.all().filter(enabled=True)[:5] cache.set(cache_key, images) return {'images': images} Any idea what could be the problem, from the error message below it looks like there's an issue in django's cache.py?

    Read the article

  • django test client trouble

    - by Anton Koval'
    I've got a problem... we're writing project using django, and i'm trying to use django.test.client with nose test-framework for tests. Our code is like this: from simplejson import loads from urlparse import urljoin from django.test.client import Client TEST_URL = "http://smakly.localhost:9090/" def test_register(): cln = Client() ref_data = {"email": "[email protected]", "name": "???????", "website": "http://hot.bear.com", "xhr": "true"} print urljoin(TEST_URL, "/accounts/register/") response = loads(cln.post(urljoin(TEST_URL, "/accounts/register/"), ref_data)) print response["message"] and in nose output I catch: Traceback (most recent call last): File "/home/psih/work/svn/smakly/eggs/nose-0.11.1-py2.6.egg/nose/case.py", line 183, in runTest self.test(*self.arg) File "/home/psih/work/svn/smakly/src/smakly.tests/smakly/tests/frontend/test_profile.py", line 25, in test_register response = loads(cln.post(urljoin(TEST_URL, "/accounts/register/"), ref_data)) File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 313, in post response = self.request(**r) File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 225, in request response = self.handler(environ) File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 69, in __call__ response = self.get_response(request) File "/home/psih/work/svn/smakly/parts/django/django/core/handlers/base.py", line 78, in get_response urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) File "/home/psih/work/svn/smakly/parts/django/django/utils/functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' My settings.py file does have this attribute. If I get the data from the server with standard urllib2.urllopen().read() it works in the proper way. Any ideas how I can solve this case?

    Read the article

  • How to filter queryset in changelist_view in django admin?

    - by minder
    Let's say I have a site where Users can add Entries through admin panel. Each User has his own Category he is responsible for (each Category has an Editor assigned through ForeingKey/ManyToManyField). When User adds Entry, I limit the choices by using EntryAdmin like this: class EntryAdmin(admin.ModelAdmin): (...) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'category': if request.user.is_superuser: kwargs['queryset'] = Category.objects.all() else: kwargs['queryset'] = Category.objects.filter(editors=request.user) return db_field.formfield(**kwargs) return super(EntryAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) This way I can limit the categories to which a User can add Entry and it works perfect. Now the tricky part: On the Entry changelist/action page I want to show only those Entries which belong to current User's Category. I tried to do this using this method: def changelist_view(self, request, extra_context=None): if not request.user.is_superuser: self.queryset = self.queryset.filter(editors=request.user) But I get this error: AttributeError: 'function' object has no attribute 'filter' This is strange, because I thought it should be a typical QuerySet. Basically such methods are not well documented and digging through tons of Django code is not my favourite sport. Any ideas how can I achieve my goal?

    Read the article

  • Django custom managers - how do I return only objects created by the logged-in user?

    - by Tom Tom
    I want to overwrite the custom objects model manager to only return objects a specific user created. Admin users should still return all objects using the objects model manager. Now I have found an approach that could work. They propose to create your own middleware looking like this: #### myproject/middleware/threadlocals.py try: from threading import local except ImportError: # Python 2.3 compatibility from django.utils._threading_local import local _thread_locals = local() def get_current_user(): return getattr(_thread_locals, 'user', None) class ThreadLocals(object): """Middleware that gets various objects from the request object and saves them in thread local storage.""" def process_request(self, request): _thread_locals.user = getattr(request, 'user', None) #### end And in the Custom manager you could call the get_current_user() method to return only objects a specific user created. class UserContactManager(models.Manager): def get_query_set(self): return super(UserContactManager, self).get_query_set().filter(creator=get_current_user()) Is this a good approach to this use-case? Will this work? Or is this like "using a sledgehammer to crack a nut" ? ;-) Just using: Contact.objects.filter(created_by= user) in each view doesn`t look very neat to me. EDIT Do not use this middleware approach !!! use the approach stated by Jack M. below After a while of testing this approach behaved pretty strange and with this approach you mix up a global-state with a current request. Use the approach presented below. It is really easy and no need to hack around with the middleware. create a custom manager in your model with a function that expects the current user or any other user as an input. #in your models.py class HourRecordManager(models.Manager): def for_user(self, user): return self.get_query_set().filter(created_by=user) class HourRecord(models.Model): #Managers objects = HourRecordManager() #in vour view you can call the manager like this and get returned only the objects from the currently logged-in user. hr_set = HourRecord.objects.for_user(request.user)

    Read the article

  • Django: TypeError: 'str' object is not callable, referer: http://xxx

    - by user705415
    I've been wondering why when I set the settings.py of my django project 'arvindemo' debug = Flase and deploy it on Apache with mod_wsgi, I got the 500 Internal Server Error. Env: Django 1.4.0 Python 2.7.2 mod_wsgi 2.8 OS centOS Here is the recap: Visit the homepage, go to sub page A/B/C/D, and fill some forms, then submit it to the Apache server. Once click 'submit' button, I will get the '500 Internal Server Error', and the error_log listed below(Traceback): [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] Traceback (most recent call last): [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__ [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] response = self.get_response(request) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 179, in get_response [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 224, in handle_uncaught_exception [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] if resolver.urlconf_module is None: [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 323, in urlconf_module [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] self._urlconf_module = import_module(self.urlconf_name) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/python2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] __import__(name) [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] File "/opt/web/django/arvindemo/arvindemo/../arvindemo/urls.py", line 23, in <module> [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] url(r'^submitPage$', name=submitPage), [Tue Apr 10 10:07:20 2012] [error] [client 122.198.133.250] TypeError: url() takes at least 2 arguments (2 given) When using django runserver, I set arvindemo.settings debug = True, everything is OK. But things changed once I set debug = Flase. Here is my views.py from django.http import HttpResponseRedirect from django.http import HttpResponse, HttpResponseServerError from django.shortcuts import render_to_response import datetime, string from user_info.models import * from django.template import Context, loader, RequestContext import settings def hello(request): return HttpResponse("hello girl") def helpPage(request): return render_to_response('kktHelp.html') def server_error(request, template_name='500.html'): return render_to_response(template_name, context_instance = RequestContext(request) ) def page404(request): return render_to_response('404.html') def submitPage(request): post = request.POST Mall = 'goodsName' Contest = 'ojs' Presentation = 'addr' WeatherReport = 'city' Habit = 'task' if Mall in post: return submitMall(request) elif Contest in post: return submitContest(request) elif Presentation in post: return submitPresentation(request) elif Habit in post: return submitHabit(request) elif WeatherReport in post: return submitWeather(request) else: return HttpResponse(request.POST) return HttpResponseRedirect('404') def submitXXX(): ..... def xxxx(): .... Here comes the urls.py from django.conf.urls import patterns, include, url from views import * from django.conf import settings handler500 = 'server_error' urlpatterns = patterns('', url(r'^hello/$', hello), # hello world url(r'^$', homePage), url(r'^time/$', getTime), url(r'^time/plus/(\d{1,2})/$', hoursAhead), url(r'^Ttime/$', templateGetTime), url(r'^Mall$', templateMall), url(r'^Contest$', templateContest), url(r'^Presentation$', templatePresentation), url(r'^Habit$', templateHabit), url(r'^Weather$', templateWeather), url(r'^Help$', helpPage), url(r'^404$', page404), url(r'^500$', server_error), url(r'^submitPage$', submitPage), url(r'^submitMall$', submitMall), url(r'^submitContest$', submitContest), url(r'^submitPresentation$', submitPresentation), url(r'^submitHabit$', submitHabit), url(r'^submitWeather$', submitWeather), url(r'^terms$', terms), url(r'^privacy$', privacy), url(r'^thanks$', thanks), url(r'^about$', about), url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATICFILES_DIRS}), ) I'm sure there is no syntax error in my django project,cause when I use django runserver, everything is fine. Anyone can help ? Best regards

    Read the article

  • How can I handle dynamic calculated attributes in a model in Django?

    - by bullfish
    In Django I calculate the breadcrumb (a list of fathers) for an geographical object. Since it is not going to change very often, I am thinking of pre calculating it once the object is saved or initialized. 1.) What would be better? Which solution would have a better performance? To calculate it at _init_ or to calculate it when the object is saved (the object takes about 500-2000 characters in the DB)? 2.) I tried to overwrite the _init_ or save() methods but I don't know how to use attributes of the just saved object. Accessing *args, **kwargs did not work. How can I access them? Do I have to save, access the father and then save again? 3.) If I decide to save the breadcrumb. Whats the best way to do it? I used http://www.djangosnippets.org/snippets/1694/ and have crumb = PickledObjectField(). Thats the method to calculate the attribute crumb() def _breadcrumb(self): breadcrumb = [ ] x = self while True: x = x.father try: if hasattr(x, 'country'): breadcrumb.append(x.country) elif hasattr(x, 'region'): breadcrumb.append(x.region) elif hasattr(x, 'city'): breadcrumb.append(x.city) else: break except: break breadcrumb.reverse() return breadcrumb Thats my save-Method: def save(self,*args, **kwargs): # how can I access the father ob the object? father = self.father # does obviously not work father = kwargs['father'] # does not work either # the breadcrumb gets calculated here self.crumb = self._breadcrumb(father) super(GeoObject, self).save(*args,**kwargs) Please help me out. I am working on this for days now. Thank you.

    Read the article

  • How to render a POST and make it show up on another page

    - by stack5914
    I'm trying to create a marketplace website similar to craigslist. I created a form according to the Django tutorial "Working with forms", but I don't know how to render information I got from the POST forms. I want to make information(subject,price...etc) that I got from POST show up on another page like this. http://bakersfield.craigslist.org/atq/3375938126.html and, I want the "Subject"(please look at form.py) of this product(eg.1960 French Chair) to show up on another page like this. http://bakersfield.craigslist.org/ata/ } Can I get some advice to handle submitted information? Here's present codes. I'll appreciate all your answers and helps. <-! Here's my codes -- ?forms.py from django import forms class SellForm(forms.Form): subject = forms.CharField(max_length=100) price = forms.CharField(max_length=100) condition = forms.CharField(max_length=100) email = forms.EmailField() body = forms.TextField() ?views.py from django.shortcuts import render, render_to_response from django.http import HttpResponseRedirect from site1.forms import SellForm def sell(request): if request.method =="POST": form =SellForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] price = form.cleaned_data['price'] condition = form.cleaned_data['condition'] email = form.cleaned_data['email'] body = form.cleaned_data['body'] return HttpResponseRedirect('/books/') else: form=SellForm() render(request, 'sell.html',{'form':form,}) ?urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^sechand/$','site1.views.sell'), url(r'^admin/', include(admin.site.urls)), ) ?sell.html <form action = "/sell/" method = "post">{% csrf_token%} {{ form.as_p }} <input type = "submit" value="Submit" /> </form>

    Read the article

  • How to stop Django from adding extra html elements to rendered widgets.

    - by stinkypyper
    I have a Django radio button group that renders to HTML as follows: <ul> <li><label for="id_package_id_0"><input type="radio" id="id_package_id_0" value="1" name="package_id" /> Test 256</label></li> <li><label for="id_package_id_1"><input type="radio" id="id_package_id_1" value="2" name="package_id" /> Test 384</label></li> <li><label for="id_package_id_2"><input type="radio" id="id_package_id_2" value="3" name="package_id" /> Test 512</label></li> <li><label for="id_package_id_3"><input type="radio" id="id_package_id_3" value="4" name="package_id" /> Test 768</label></li> <li><label for="id_package_id_4"><input type="radio" id="id_package_id_4" value="5" name="package_id" /> Test 1024</label></li> </ul> I need it to render without being a list. I am a aware of form.as_p, form.as_table, and form.as_ul. They will not help me as they continue to add extra HTML tags. As well, I am not using the form object in it's absolute entirety, just for validation. I am doing a custom template for the form already, but wish to continue to the radio widget.

    Read the article

  • How do I set prifix to django contrib tables names?

    - by Software Enthusiastic
    HI One of my requirement is to have prefix on all the tables of the django based project (Because db is hosted on shared server). I have used db_table Meta option to set the prefix for the tables which I have created. Now my query is how do I set the prefix for tables provided by django.contrib. Instead of auth_group django should create prefix_auth_group.... How do I do that? Thank you very much...

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >