Search Results

Search found 15298 results on 612 pages for 'django template tags'.

Page 19/612 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • 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

  • template engine implementation

    - by qwerty
    I am currently building this small template engine. It takes a string containing the template in parameter, and a dictionary of "tags,values" to fill in the template. In the engine, I have no idea of the tags that will be in the template and the ones that won't. I am currently iterating (foreach) on the dictionnary, parsing my string that I have put in a string builder, and replacing the tags in the template by their corresponding value. Is there a more efficient/convenient way of doing this? I know the main drawback here is that the stringbuilder is parsed everytime entirely for each tag, which is quite bad... (I am also checking, though not included in the sample, after the process that my template does not contain any tag anymore. They are all formated in the same way: @@tag@@) //Dictionary<string, string> tagsValueCorrespondence; //string template; StringBuilder outputBuilder = new StringBuilder(template); foreach (string tag in tagsValueCorrespondence.Keys) { outputBuilder.Replace(tag, tagsValueCorrespondence[tag]); } template = outputBuilder.ToString(); Responses: @Marc: string template = "Some @@foobar@@ text in a @@bar@@ template"; StringDictionary data = new StringDictionary(); data.Add("foo", "value1"); data.Add("bar", "value2"); data.Add("foo2bar", "value3"); Output: "Some text in a value2 template" instead of: "Some @@foobar@@ text in a value2 template"

    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

  • What's the straightforward way to implement one to many editing in list_editable in django admin?

    - by Nate Pinchot
    Given the following models: class Store(models.Model): name = models.CharField(max_length=150) class ItemGroup(models.Model): group = models.CharField(max_length=100) code = models.CharField(max_length=20) class ItemType(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="item_types") item_group = models.ForeignKey(ItemGroup) type = models.CharField(max_length=100) Inline's handle adding multiple item_types to a Store nicely when viewing a single Store. The content admin team would like to be able to edit stores and their types in bulk. Is there a simple way to implement Store.item_types in list_editable which also allows adding new records, similar to horizontal_filter? If not, is there a straightforward guide that shows how to implement a custom list_editable template? I've been Googling but haven't been able to come up with anything. Also, if there is a simpler or better way to set up these models that would make this easier to implement, feel free to comment.

    Read the article

  • django url from another template than the one associated with the view-function

    - by dana
    Heyy there, i have an application, and in my urls.py i have something like that: urlpatterns = patterns('', url(r'^profile_view/(?P<id>\d+)/$', profile_view, name='profile_view'),) meaning that the profile_view function has id as a parameter. Now, i want to call that function from another template than the one associated with the def-view that has this url. How should i do that? i have to put two render_to_response to one same function, in order to render the objects from both models? thank you!

    Read the article

  • Django manager for _set in model

    - by Daniel Johansson
    Hello, I'm in the progress of learning Django at the moment but I can't figure out how to solve this problem on my own. I'm reading the book Developers Library - Python Web Development With Django and in one chapter you build a simple CMS system with two models (Story and Category), some generic and custom views together with templates for the views. The book only contains code for listing stories, story details and search. I wanted to expand on that and build a page with nested lists for categories and stories. - Category1 -- Story1 -- Story2 - Category2 - Story3 etc. I managed to figure out how to add my own generic object_list view for the category listing. My problem is that the Story model have STATUS_CHOICES if the Story is public or not and a custom manager that'll only fetch the public Stories per default. I can't figure out how to tell my generic Category list view to also use a custom manager and only fetch the public Stories. Everything works except that small problem. I'm able to create a list for all categories with a sub list for all stories in that category on a single page, the only problem is that the list contains non public Stories. I don't know if I'm on the right track here. My urls.py contains a generic view that fetches all Category objects and in my template I'm using the *category.story_set.all* to get all Story objects for that category, wich I then loop over. I think it would be possible to add a if statement in the template and use the VIEWABLE_STATUS from my model file to check if it should be listed or not. The problem with that solution is that it's not very DRY compatible. Is it possible to add some kind of manager for the Category model too that only will fetch in public Story objects when using the story_set on a category? Or is this the wrong way to attack my problem? Related code urls.py (only category list view): urlpatterns += patterns('django.views.generic.list_detail', url(r'^categories/$', 'object_list', {'queryset': Category.objects.all(), 'template_object_name': 'category' }, name='cms-categories'), models.py: from markdown import markdown import datetime from django.db import models from django.db.models import permalink from django.contrib.auth.models import User VIEWABLE_STATUS = [3, 4] class ViewableManager(models.Manager): def get_query_set(self): default_queryset = super(ViewableManager, self).get_query_set() return default_queryset.filter(status__in=VIEWABLE_STATUS) class Category(models.Model): """A content category""" label = models.CharField(blank=True, max_length=50) slug = models.SlugField() class Meta: verbose_name_plural = "categories" def __unicode__(self): return self.label @permalink def get_absolute_url(self): return ('cms-category', (), {'slug': self.slug}) class Story(models.Model): """A hunk of content for our site, generally corresponding to a page""" STATUS_CHOICES = ( (1, "Needs Edit"), (2, "Needs Approval"), (3, "Published"), (4, "Archived"), ) title = models.CharField(max_length=100) slug = models.SlugField() category = models.ForeignKey(Category) markdown_content = models.TextField() html_content = models.TextField(editable=False) owner = models.ForeignKey(User) status = models.IntegerField(choices=STATUS_CHOICES, default=1) created = models.DateTimeField(default=datetime.datetime.now) modified = models.DateTimeField(default=datetime.datetime.now) class Meta: ordering = ['modified'] verbose_name_plural = "stories" def __unicode__(self): return self.title @permalink def get_absolute_url(self): return ("cms-story", (), {'slug': self.slug}) def save(self): self.html_content = markdown(self.markdown_content) self.modified = datetime.datetime.now() super(Story, self).save() admin_objects = models.Manager() objects = ViewableManager() category_list.html (related template): {% extends "cms/base.html" %} {% block content %} <h1>Categories</h1> {% if category_list %} <ul id="category-list"> {% for category in category_list %} <li><a href="{{ category.get_absolute_url }}">{{ category.label }}</a></li> {% if category.story_set %} <ul> {% for story in category.story_set.all %} <li><a href="{{ story.get_absolute_url }}">{{ story.title }}</a></li> {% endfor %} </ul> {% endif %} {% endfor %} </ul> {% else %} <p> Sorry, no categories at the moment. </p> {% endif %} {% endblock %}

    Read the article

  • Django ImageField issue with JPEG's

    - by Kieran Lynn
    I am having a major issue with PIL (Python Image Library) in Django and have jumpped through a lot of hoops and have thus far not been able to figure out what the root of the issue is. The problem essentially breaks down to not being able to upload JPEG images through the ImageField in the Django admin. But the issue is not as simple as installing libjpeg. First, I installed PIL (through Buildout) and realized once it was installed that I had not installed libjpeg because JPEG support was not available. Having not setup the server myself, I just assumed that it was not installed and I compiled libjpeg 8 from the source. This ended up in my /usr/local/lib/ directory. I cleared out my Buildout files and rebuilt everything. This time when PIL compiled I had JPEG support. But I went to the Django Admin and tried to upload a JPEG though an ImageField with no luck. I got the "Upload a valid image. The file you uploaded was either not an image or a corrupted image" error. Just as a test I opened up a the Djano shell and ran the following: > import Image > i = Image.open( "/absolute_path/file.jpg" ) > print i <JpegImagePlugin.JpegImageFile image mode=RGB size=940x375 at 0x7F908C529BD8> This runs with no errors and shows that PIL is able to open JPEG's. After doing some reading, I come across this thread: Is it possible to control which libraries apache uses? Looks like PHP also uses libjpeg and is loading before Django, and therefor loading libjpeg 6.2 before. This is show when using lsof: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME apache2 2561 www-data mem REG 202,1 146032 639276 /usr/lib/libjpeg.so.62.0.0 So my thought is that I should be using libjpeg 6.2. So I removed libjpeg located in my /usr/local/lib directory. After rereading the PIL installation instructions, I realized that I might not have the dev/header files for libjpeg that PIL needs. So I also uninstalled libjpeg using the aptitude uninstaller (sudo aptitude remove libjpeg62). Then to ensure that I got the header files that PIL needed I installed libjpeg using aptitude: (sudo aptget install libjpeg62-dev). From here I cleaned out my Buildout directory, and reran Buildout, which in turn reinstalled PIL. Once again, I have JPEG support, now using the libjpeg62. So I go to test in the Django Admin. Still no JPEG support. So I wanted to test JPEG support in general and see if the exception was not handled, what kind of error it would throw. So in my homepage view I added the following code to open a JPEG image: import Image i = Image.open( "/absolute_path/file.jpg" ) v = i.verify() Then I pass i to the HTML view just to easily see the output. I deploy these changes to the server and restart. I am surprised not to see an error and get the following output: {{ i }} - <JpegImagePlugin.JpegImageFile image mode=RGB size=940x375 at 0x7F908C529BD8> {{ v }} - None So at this point I am really confused: Why can I successfully open a JPEG while the admin cannot? Am I missing something, is this not an issue with libjpeg? If not an issue with libjpeg, why can I upload a PNG with no issues? Any help would be much appreciated, I have been on this for 2 days debugging with no luck. Setup: 1. Rackspace Cloud Server 2. Ubuntu 10.04 3. Django 1.2.3 (Installed though Buildout) 4. PIL 1.1.7 (Installed though Buildout) 5. libjpeg 6.2 (installed through aptitude (sudo aptget install libjpeg62-dev)

    Read the article

  • Problem trying to achieve a join using the `comments` contrib in Django

    - by NiKo
    Hi, Django rookie here. I have this model, comments are managed with the django_comments contrib: class Fortune(models.Model): author = models.CharField(max_length=45, blank=False) title = models.CharField(max_length=200, blank=False) slug = models.SlugField(_('slug'), db_index=True, max_length=255, unique_for_date='pub_date') content = models.TextField(blank=False) pub_date = models.DateTimeField(_('published date'), db_index=True, default=datetime.now()) votes = models.IntegerField(default=0) comments = generic.GenericRelation( Comment, content_type_field='content_type', object_id_field='object_pk' ) I want to retrieve Fortune objects with a supplementary nb_comments value for each, counting their respectve number of comments ; I try this query: >>> Fortune.objects.annotate(nb_comments=models.Count('comments')) From the shell: >>> from django_fortunes.models import Fortune >>> from django.db.models import Count >>> Fortune.objects.annotate(nb_comments=Count('comments')) [<Fortune: My first fortune, from NiKo>, <Fortune: Another One, from Dude>, <Fortune: A funny one, from NiKo>] >>> from django.db import connection >>> connection.queries.pop() {'time': '0.000', 'sql': u'SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21'} Below is the properly formatted sql query: SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21 Can you spot the problem? Django won't LEFT JOIN the django_comments table with the content_type data (which contains a reference to the fortune one). This is the kind of query I'd like to be able to generate using the ORM: SELECT "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", COUNT("django_comments"."id") AS "nb_comments" FROM "django_fortunes_fortune" LEFT OUTER JOIN "django_comments" ON ("django_fortunes_fortune"."id" = "django_comments"."object_pk") LEFT OUTER JOIN "django_content_type" ON ("django_comments"."content_type_id" = "django_content_type"."id") GROUP BY "django_fortunes_fortune"."id", "django_fortunes_fortune"."author", "django_fortunes_fortune"."title", "django_fortunes_fortune"."slug", "django_fortunes_fortune"."content", "django_fortunes_fortune"."pub_date", "django_fortunes_fortune"."votes" LIMIT 21 But I don't manage to do it, so help from Django veterans would be much appreciated :) Hint: I'm using Django 1.2-DEV Thanks in advance for your help.

    Read the article

  • Django: Create custom template tag -> ImportError

    - by Alexander Scholz
    I'm sorry to ask this again, but I tried several solutions from stack overflow and some tutorials and I couldn't create a custom template tag yet. All I get is ImportError: No module named test_tag when I try to start the server via python manage.py runserver. I created a very basic template tag (found here: django templatetag?) like so: My folder structure: demo manage.py test __init__.py settings.py urls.py ... templatetags __init__.py test_tag.py test_tag.py: from django import template register = template.Library() @register.simple_tag def test_tag(input): if "foo" == input: return "foo" if "bar" == input: return "bar" if "baz" == input: return "baz" return "" index.html: {% load test_tag %} <html> <head> ... </head> <body> {% cms_toolbar %} {% foobarbaz "bar" %} {% foobarbaz "elephant" %} {% foobarbaz "foo" %} </body> </html> and my settings.py: INSTALLED_APPS = ( ... 'test_tag', ... ) Please let me know if you need further information from my settings.py and what I did wrong so I can't even start my server. (If I delete 'test_tag' from installed apps I can start the server but I get the error that test_tag is not known, of course). Thanks

    Read the article

  • Certificate Template Missing from "Certificate Template to Issue"

    - by Adam Robinson
    I'm having a problem similar to that posted in this question: Missing Certificate template From certificate to issue The short version is that I've created a duplicate certificate template and I'm trying to add it to my domain CA so that I can issue certificates with it. However, when I go into the Certification Authority MMC and go to "Certificate Templates - New - Certificate Template To Issue", my template is missing (along with quite a number of other templates that are present in the domain). Unlike the previous question, however, my CA is running on Server 2008 R2 Enterprise. Our organization has a single DC and a single CA, so I'm not seeing where there could be propagation delay. Any ideas how to get my template to show so that I can issue certificates?

    Read the article

  • How do I add a trailing slash for Django MPTT-based categorization app?

    - by Patrick Beeson
    I'm using Django-MPTT to develop a categorization app for my Django project. But I can't seem to get the regex pattern for adding a trailing slash that doesn't also break on child categories. Here's an example URL: http://mydjangoapp.com/categories/parentcat/childcat/ I'd like to be able to use http://mydjangoapp.com/categories/parentcat and have it redirect to the trailing slash version. The same should apply to http://mydjangoapp.com/categories/parentcat/childcat (it should redirect to http://mydjangoapp.com/categories/parentcat/childcat/). Here's my urls.py: from django.conf.urls.defaults import patterns, include, url from django.views.decorators.cache import cache_page from storefront.categories.models import Category from storefront.categories.views import SimpleCategoryView urlpatterns = patterns('', url(r'^(?P<full_slug>[-\w/]+)', cache_page(SimpleCategoryView.as_view(), 60 * 15), name='category_view'), ) And here is my view: from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.views.generic import TemplateView, DetailView from django.views.generic.detail import SingleObjectTemplateResponseMixin, SingleObjectMixin from django.utils.translation import ugettext as _ from django.contrib.syndication.views import Feed from storefront.categories.models import Category class SimpleCategoryView(TemplateView): def get_category(self): return Category.objects.get(full_slug=self.kwargs['full_slug']) def get_context_data(self, **kwargs): context = super(SimpleCategoryView, self).get_context_data(**kwargs) context["category"] = self.get_category() return context def get_template_names(self): if self.get_category().template_name: return [self.get_category().template_name] else: return ['categories/category_detail.html'] And finally, my model: from django.db import models from mptt.models import MPTTModel from mptt.fields import TreeForeignKey class CategoryManager(models.Manager): def get(self, **kwargs): defaults = {} defaults.update(kwargs) if 'full_slug' in defaults: if defaults['full_slug'] and defaults['full_slug'][-1] != "/": defaults['full_slug'] += "/" return super(CategoryManager, self).get(**defaults) class Category(MPTTModel): title = models.CharField(max_length=255) description = models.TextField(blank=True, help_text='Please use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for all text-formatting and links. No HTML is allowed.') slug = models.SlugField(help_text='Prepopulates from title field.') full_slug = models.CharField(max_length=255, blank=True) template_name = models.CharField(max_length=70, blank=True, help_text="Example: 'categories/category_parent.html'. If this isn't provided, the system will use 'categories/category_detail.html'. Use 'categories/category_parent.html' for all parent categories and 'categories/category_child.html' for all child categories.") parent = TreeForeignKey('self', null=True, blank=True, related_name='children') objects = CategoryManager() class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def save(self, *args, **kwargs): orig_full_slug = self.full_slug if self.parent: self.full_slug = "%s%s/" % (self.parent.full_slug, self.slug) else: self.full_slug = "%s/" % self.slug obj = super(Category, self).save(*args, **kwargs) if orig_full_slug != self.full_slug: for child in self.get_children(): child.save() return obj def available_product_set(self): """ Returns available, prioritized products for a category """ from storefront.apparel.models import Product return self.product_set.filter(is_available=True).order_by('-priority') def __unicode__(self): return "%s (%s)" % (self.title, self.full_slug) def get_absolute_url(self): return '/categories/%s' % (self.full_slug)

    Read the article

  • Django + FastCGI - randomly raising OperationalError

    - by ibz
    I'm running a Django application. Had it under Apache + mod_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume it has something to do with some settings. Found a few results when googleing, but they seem to be related to setting maxrequests=1. However, I use the default, which is 0. Any ideas where to look for? PS. I'm using PostgreSQL. Might be related to that as well, since the exception appears when making a database query. Thanks. File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 86, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 140, in root if not self.has_permission(request): File "/usr/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 99, in has_permission return request.user.is_authenticated() and request.user.is_staff File "/usr/lib/python2.6/site-packages/django/contrib/auth/middleware.py", line 5, in __get__ request._cached_user = get_user(request) File "/usr/lib/python2.6/site-packages/django/contrib/auth/__init__.py", line 83, in get_user user_id = request.session[SESSION_KEY] File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 46, in __getitem__ return self._session[key] File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/base.py", line 172, in _get_session self._session_cache = self.load() File "/usr/lib/python2.6/site-packages/django/contrib/sessions/backends/db.py", line 16, in load expire_date__gt=datetime.datetime.now() File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line 93, in get return self.get_query_set().get(*args, **kwargs) File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 304, in get num = len(clone) File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 160, in __len__ self._result_cache = list(self.iterator()) File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 275, in iterator for row in self.query.results_iter(): File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 206, in results_iter for rows in self.execute_sql(MULTI): File "/usr/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1734, in execute_sql cursor.execute(sql, params) OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.

    Read the article

  • Apps not showing in Django admin site

    - by jack
    I have a Django project with about 10 apps in it. But the admin interface only shows Auth and Site models which are part of Django distribution. Yes, the admin interface is up and working but none of my self-written apps shows there. INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.admindocs', 'project.app1', ... app1/admin.py from django.contrib import admin from project.app1.models import * admin.site.register(model1) admin.site.register(model2) admin.site.register(model3) What could be wrong in this case? Looks like everything is configured as what document says. Thank you in advance.

    Read the article

  • Django and App Engine

    - by notnoop
    I wanted to check the status of running Django on the Google App Engine currently and what the benefits of running django on GAE over simply using Webapp. Django main killer feature, IMHO, is the reuseable apps and middleware. Unfortunately, most current Django apps use models or model forms (django-tags, django-reviews, django-profiles, Pinax apps). So what are the remaining features or benefits that django has that can still run in Google App Engine (other than what's disabled: the popular django apps, session and authentication middleware, users and admin, models, etc). Also, is there a list of the Django apps that work in App Engine as well?

    Read the article

  • review on django book vs django tutorial

    - by momo
    going through both the django book and tutorial, am a bit confused to the differences in approach (aren't they both written by the same people?) can anyone who has experience in both give a short review on them? i have decent python skills (largely untested though), but no experience at all in web apps and am trying to decide which one to stick to. i briefly looked in to practical django projects but that was a bit too complicated for me, my background is primarily bash scripting, the python i know i learned from an instant hacking tutorial and diving into python.

    Read the article

  • Django: How do I position a page when using Django templates

    - by swisstony
    I have a web page where the user enters some data and then clicks a submit button. I process the data and then use the same Django template to display the original data, the submit button, and the results. When I am using the Django template to display results, I would like the page to be automatically scrolled down to the part of the page where the results begin. This allows the user to scroll back up the page if she wants to change her original data and click submit again. Hopefully, there's some simple way of doing this that I can't see at the moment.

    Read the article

  • Django: request object to template context transparancy

    - by anars
    Hi! I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views: render_to_response(...., ( {'menu': RequestContext(request)})) The request object contains the key,value pair which is injected using a custom context processor. While this works, I had hoped there was a more generic way of passing selected parts of the request object to the template context. I've tried passing it by generic views, but as it turns out the request object isn't instantiated when parsing the urlpatterns list.

    Read the article

  • Notepad++ tabbing out of tags, autocomplete

    - by Matt
    I'm trying to learn a little HTML. Everyone says to use Notepad++ over notepad. I have autocomplete on. My question: When I type my opening tag and Notepad++ then puts"""" closing tag, how do I "jump" out of the tag when I'm done typing? If I tab or hit enter, I'm still stuck before the closing tag. I can use my arrow keys, but if I'm going to do that, I would rather just type the closing tags. Also if I have an UL of 10 items, and I want to change it to an OL, how do I select both the opening and closing tags so I may edit them at the same time? Thanks PS I wasn't able to post the HTML tags.

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >