Search Results

Search found 8610 results on 345 pages for 'django filter'.

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

  • Django syncdb not making tables for my app

    - by Rosarch
    It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp', 'django.contrib.admin', ) What could I be doing wrong? The break appeared to coincide with editing this model in models.py, but that could be total coincidence. I commented out the lines I changed, and it still doesn't work. class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(Course, through=TakingCourse, blank=True) school = models.ForeignKey(School) # minCreditsPerTerm = models.IntegerField(blank=True) # maxCreditsPerTerm = models.IntegerField(blank=True) # optimalCreditsPerTerm = models.IntegerField(blank=True) UPDATE: When I run python manage.py loadddata initial_data, it gives an error: DeserializationError: Invalid model identifier: myapp.SomeModel Loading this data had worked fine before. This error is thrown on the very first data object in the data file.

    Read the article

  • Django ORM and PostgreSQL connection limits

    - by bennylope
    I'm running a Django project on Postgresql 8.1.21 (using Django 1.1.1, Python2.5, psycopg2, Apache2 with mod_wsgi 3.2). We've recently encountered this lovely error: OperationalError: FATAL: connection limit exceeded for non-superusers I'm not the first person to run up against this. There's a lot of discussion about this error, specifically with psycopg, but much of it centers on older versions of Django and/or offer solutions involving edits to code in Django itself. I've yet to find a succinct explanation of how to solve the problem of the Django ORM (or psycopg, whichever is really responsible, in this case) leaving open Postgre connections. Will simply adding connection.close() at the end of every view solve this problem? Better yet, has anyone conclusively solved this problem and kicked this error's ass?

    Read the article

  • View centric design with Django

    - by wishi_
    Hi! I'm relatively new to Django and I'm designing a website that primarily needs usability experience, speaking of optimized CSS, HTML5 and UI stuff. It's very easy to use Django for data/Model centric design. Just designing a couple of Python classes and ./manage.py syncdb - there's your Model. But I'm dealing with a significant amount of View centric challenges. (Different user classes, different tasks, different design challenges.) The official Django tutorial cursorily goes through using a "Template". Is there any Design centric guide for Django, or a set of Templates that are ready and useable? I don't want to start from scratch using JS, HTML5, Ajax and everything. From the Model layer perspective Django is very rapid and delivering a working base system. I wonder whether there's something like that for the Views.

    Read the article

  • django newbie question : cant start a new project

    - by Moayyad Yaghi
    hello . I'm totally new to django . and I'm using its documentation to get help on how to use it but seems like something is missing. i installed django using setup.py install command and i added the ( django/bin ) to system path variable but. i still cant start a new project i use the following syntax to start a project : django-admin.py startproject myNewProject but it says Type 'django-admin.py help' for usage. 1 do i miss anything ? thank u

    Read the article

  • Django filters - Using an AllValuesFilter (with a LinkWidget) on a ManyToManyField

    - by magnetix
    This is my first Stack Overflow question, so please let me know if I do anything wrong. I wish to create an AllValues filter on a ManyToMany field using the wonderful django-filters application. Basically, I want to create a filter that looks like it does in the Admin, so I also want to use the LinkWidget too. Unfortunately, I get an error (Invalid field name: 'operator') if I try this the standard way: # Models class Organisation(models.Model): name = models.CharField() ... class Sign(models.Model): name = models.CharField() operator = models.ManyToManyField('Organisation', blank=True) ... # Filter class SignFilter(LinkOrderFilterSet): operator = django_filters.AllValuesFilter(widget=django_filters.widgets.LinkWidget) class Meta: model = Sign fields = ['operator'] I got around this by creating my own filter with the many to many relationship hard coded: # Models class Organisation(models.Model): name = models.CharField() ... class Sign(models.Model): name = models.CharField() operator = models.ManyToManyField('Organisation', blank=True) ... # Filter class MyFilter(django_filters.ChoiceFilter): @property def field(self): cd = {} for row in self.model.objects.all(): orgs = row.operator.select_related().values() for org in orgs: cd[org['id']] = org['name'] choices = zip(cd.keys(), cd.values()) list.sort(choices, key=lambda x:(x[1], x[0])) self.extra['choices'] = choices return super(AllValuesFilter, self).field class SignFilter(LinkOrderFilterSet): operator = MyFilter(widget=django_filters.widgets.LinkWidget) I am new to Python and Django. Can someone think of a more generic/elegant way of doing this?

    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

  • 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 filter bool not iterable

    - by dana
    I want to filter all Relation Objects where (relation= following relation in a virtual community) the date one has initiated the following is in the past, related to the moment now. The following declaration seems to be wrong, as a bool object is not iterable. Is there another way to do that? d = Relations.objects.filter(date_follow < datetime.now())

    Read the article

  • Apply LADSPA filter to only one channel of multichannel output with Alsa and PulseAudio

    - by justinzane
    I want to apply a filter, specifically SWH's glame-bandpass-iir, to only one of several output channels. I want unfiltered output to go to the front, rear and LFE channels with bandpass filtered output for the center channel. I'm assuming that this needs to be done with Alsa's /etc/asound.conf but I cannot understand the documentation well enough to figure out how. If there is a better way, via PulseAudio, Jack or whatever, I'm open to whatever works. Thanks.

    Read the article

  • Django Form for date range

    - by gramware
    I am trying to come up with a form that lets the user select a date range to generate a web query in Django. I am having errors getting the date to filter with in my view, I am unable to strip the date. Here is my forms.py class ReportFiltersForm(forms.Form): start_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget()) end_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget()) And my view if request.method == 'POST': form = ReportFiltersForm(request.POST) sdy = request.POST['start_date_year'] sdm = request.POST['start_date_month'] sdd = request.POST['start_date_day'] edy = request.POST['end_date_year'] edm = request.POST['end_date_month'] edd = request.POST['end_date_day'] start_date= datetime.date(sdy, sdm, sdd) end_date= datetime.date(edy, edm,edd) Traceback Traceback (most recent call last): File "/usr/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 651, in __call__ return self.application(environ, start_response) File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__ response = self.get_response(request) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response return self.handle_uncaught_exception(request, resolver, exc_info) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 92, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/projects/acms/cms/views.py", line 470, in eventreports start_date= datetime.date(sdy, sdm, sdd) TypeError: an integer is required

    Read the article

  • Detect the language & django locale-url

    - by mamcx
    I want to deploy a website in english & spanish and detect the user browser languaje & redirect to the correct locale site. My site is www.elmalabarista.com I install django-localeurl, but I discover that the languaje is not correctly detected. This are my middlewares: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'multilingual.middleware.DefaultLanguageMiddleware', 'middleware.feedburner.FeedburnerMiddleware', 'lib.threadlocals.ThreadLocalsMiddleware', 'middleware.url.UrlMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'maintenancemode.middleware.MaintenanceModeMiddleware', 'middleware.redirect.RedirectMiddleware', 'openidconsumer.middleware.OpenIDMiddleware', 'django.middleware.doc.XViewMiddleware', 'middleware.ajax_errors.AjaxMiddleware', 'pingback.middleware.PingbackMiddleware', 'localeurl.middleware.LocaleURLMiddleware', 'multilingual.flatpages.middleware.FlatpageFallbackMiddleware', 'django.middleware.common.CommonMiddleware', ) But ALWAYS the site get to US despite the fact my OS & Browser setup is spanish. LANGUAGES = ( ('en', ugettext('English')), ('es', ugettext('Spanish')), ) DEFAULT_LANGUAGE = 1 Then, I hack the middleware of locale-url and do this: def process_request(self, request): locale, path = self.split_locale_from_request(request) if request.META.has_key('HTTP_ACCEPT_LANGUAGE'): locale = utils.supported_language(request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0]) locale_path = utils.locale_path(path, locale) if locale_path != request.path_info: if request.META.get("QUERY_STRING", ""): locale_path = "%s?%s" % (locale_path, request.META['QUERY_STRING']) return HttpResponseRedirect(locale_path) request.path_info = path if not locale: locale = settings.LANGUAGE_CODE translation.activate(locale) request.LANGUAGE_CODE = translation.get_language() However, this detect fine the language but redirect the "en" urls to "es". So is impossible navigate in english. UPDATE: This is the final code (after the input from Carl Meyer) with a fix for the case of "/": def process_request(self, request): locale, path = self.split_locale_from_request(request) if (not locale) or (locale==''): if request.META.has_key('HTTP_ACCEPT_LANGUAGE'): locale = utils.supported_language(request.META['HTTP_ACCEPT_LANGUAGE'].split(',')[0]) else: locale = settings.LANGUAGE_CODE locale_path = utils.locale_path(path, locale) if locale_path != request.path_info: if request.META.get("QUERY_STRING", ""): locale_path = "%s?%s" % (locale_path, request.META['QUERY_STRING']) return HttpResponseRedirect(locale_path) request.path_info = path translation.activate(locale) request.LANGUAGE_CODE = translation.get_language()

    Read the article

  • UnicodeDecodeError on attempt to save file through django default filebased backend

    - by Ivan Kuznetsov
    When i attempt to add a file with russian symbols in name to the model instance through default instance.file_field.save method, i get an UnicodeDecodeError (ascii decoding error, not in range (128) from the storage backend (stacktrace ended on os.exist). If i write this file through default python file open/write all goes right. All filenames in utf-8. I get this error only on testing Gentoo, on my Ubuntu workstation all works fine. class Article(models.Model): file = models.FileField(null=True, blank=True, max_length = 300, upload_to='articles_files/%Y/%m/%d/') Traceback: File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 24. return view_func(request, *args, **kwargs) File "/var/www/localhost/help/wiki/views.py" in edit_article 338. new_article.file.save(fp, fi, save=True) File "/usr/lib/python2.6/site-packages/django/db/models/fields/files.py" in save 92. self.name = self.storage.save(name, content) File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in save 47. name = self.get_available_name(name) File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in get_available_name 73. while self.exists(name): File "/usr/lib/python2.6/site-packages/django/core/files/storage.py" in exists 196. return os.path.exists(self.path(name)) File "/usr/lib/python2.6/genericpath.py" in exists 18. st = os.stat(path) Exception Type: UnicodeEncodeError at /edit/ Exception Value: ('ascii', u'/var/www/localhost/help/i/articles_files/2010/03/17/\u041f\u0440\u0438\u0432\u0435\u0442', 52, 58, 'ordinal not in range(128)')

    Read the article

  • Django facebook integration error

    - by Gaurav
    I'm trying to integrate facebook into my application so that users can use their FB login to login to my site. I've got everything up and running and there are no issues when I run my site using the command line python manage.py runserver But this same code refuses to run when I try and run it through Apache. I get the following error: Environment: Request Method: GET Request URL: http://helvetica/foodfolio/login Django Version: 1.1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'foodfolio.app', 'foodfolio.facebookconnect'] Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'facebook.djangofb.FacebookMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebookconnect.middleware.FacebookConnectMiddleware') Template error: In template /home/swat/website-apps/foodfolio/facebookconnect/templates/facebook/js.html, error at line 2 Caught an exception while rendering: No module named app.models 1 : <script type="text/javascript"> 2 : FB_RequireFeatures(["XFBML"], function() {FB.Facebook.init("{{ facebook_api_key }}", " {% url facebook_xd_receiver %} ")}); 3 : 4 : function facebookConnect(loginForm) { 5 : FB.Connect.requireSession(); 6 : FB.Facebook.get_sessionState().waitUntilReady(function(){loginForm.submit();}); 7 : } 8 : function pushToFacebookFeed(data){ 9 : if(data['success']){ 10 : var template_data = data['template_data']; 11 : var template_bundle_id = data['template_bundle_id']; 12 : feedTheFacebook(template_data,template_bundle_id,function(){}); Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/swat/website-apps/foodfolio/app/controller.py" in __showLogin__ 238. context_instance = RequestContext(request)) File "/usr/lib/pymodules/python2.6/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/pymodules/python2.6/django/template/loader.py" in render_to_string 108. return t.render(context_instance) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 946. autoescape=context.autoescape)) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 81. raise wrapped Exception Type: TemplateSyntaxError at /foodfolio/login Exception Value: Caught an exception while rendering: No module named app.models

    Read the article

  • Javascript error when integrating django-tinymce and django-filebrowser

    - by jwesonga
    I've set up django-filebrowser in my app without any bugs, I already had django-tinymce set up and it loads the editor in the admin forms. I now want to use django-filebrowser with django-tinymce, but I keep getting a weird javascript error when I click on "Image URL" in the Image popup: r is undefined the error is js/tiny_mce/tiny_mce.js My settings.py file has the following configuration: TINYMCE_JS_URL=MEDIA_URL + 'js/tiny_mce/tiny_mce.js' TINYMCE_DEFAULT_CONFIG = { 'mode': "textareas", 'theme': "advanced", 'language': "en", 'skin': "o2k7", 'dialog_type': "modal", 'object_resizing': True, 'cleanup_on_startup': True, 'forced_root_block': "p", 'remove_trailing_nbsp': True, 'theme_advanced_toolbar_location': "top", 'theme_advanced_toolbar_align': "left", 'theme_advanced_statusbar_location': "none", 'theme_advanced_buttons1': "formatselect,styleselect,bold,italic,underline,bullist,numlist,undo,redo,link,unlink,image,code,template,visualchars,fullscreen,pasteword,media,search,replace,charmap", 'theme_advanced_buttons2': "", 'theme_advanced_buttons3': "", 'theme_advanced_path': False, 'theme_advanced_blockformats': "p,h2,h3,h4,div,code,pre", 'width': '700', 'height': '300', 'plugins': "advimage,advlink,fullscreen,visualchars,paste,media,template,searchreplace", 'advimage_update_dimensions_onchange': True, 'file_browser_callback': "CustomFileBrowser", 'relative_urls': False, 'valid_elements' : "" + "-p," + "a[href|target=_blank|class]," + "-strong/-b," + "-em/-i," + "-u," + "-ol," + "-ul," + "-li," + "br," + "img[class|src|alt=|width|height]," + "-h2,-h3,-h4," + "-pre," + "-code," + "-div", 'extended_valid_elements': "" + "a[name|class|href|target|title|onclick]," + "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]," + "br[clearfix]," + "-p[class<clearfix?summary?code]," + "h2[class<clearfix],h3[class<clearfix],h4[class<clearfix]," + "ul[class<clearfix],ol[class<clearfix]," + "div[class]," } TINYMCE_FILEBROWSER = False TINYMCE_COMPRESSOR = False i've tried switching back to older versions of tinyMCE Javascript but nothing seems to work. Would appreciate some help

    Read the article

  • While trying to set up Django on Windows: AttributeError: 'Settings' object has no attribute 'DATABA

    - by user326370
    I'm following these instructions in order to set up Django on Windows. I have installed Python 2.6, PostgreSQL 8.4, Psycopg 2.0.14 for Python 2.6 and the latest version of Django from SVN. I'm now following these instructions to run a test project (copied from the page linked to above): C:\Documents and Settings\John>cd C:\ C:\>mkdir django C:\>cd django C:\django>django-admin.py startproject testproject C:\django>cd testproject C:\django\testproject>python manage.py runserver When I run the last line, this is the output: Validating models... Unhandled exception in thread started by <function inner_run at 0x01ECB930> Traceback (most recent call last): File "J:\Python26\lib\site-packages\django\core\management\commands\runserver.py", line 48, in inn er_run self.validate(display_num_errors=True) File "J:\Python26\lib\site-packages\django\core\management\base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "J:\Python26\lib\site-packages\django\core\management\validation.py", line 22, in get_validat ion_errors from django.db import models, connection File "J:\Python26\lib\site-packages\django\db\__init__.py", line 14, in <module> if not settings.DATABASES: File "J:\Python26\lib\site-packages\django\utils\functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'DATABASES' Did I forget to do something with the database? Any help will be appreciated. Thank you!

    Read the article

  • How to do custom display and auto-select in django admin multi-select field?

    - by rsp
    I'm new to django, so please feel free to tell me if I'm doing this incorrectly. I am trying to create a django ordering system. My order model: class Order(models.Model): ordered_by = models.ForeignKey(User, limit_choices_to = {'groups__name': "Managers", 'is_active': 1}) in my admin ANY user can enter an order, but ordered_by must be someone in the group "managers" (this is the behavior I want). Now, if the logged in user happens to be a manager I want it to automatically fill in the field with that logged in user. I have accomplished this by: class OrderAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "ordered_by": if request.user in User.objects.filter(groups__name='Managers', is_active=1): kwargs["initial"] = request.user.id kwargs["empty_label"] = "-------------" return db_field.formfield(**kwargs) return super(OrderAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) This also works, but the admin puts the username as the display for the select box by default. It would be nice to have the user's real name listed. I was able to do it with this: class UserModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.first_name + " " + obj.last_name class OrderForm(forms.ModelForm): ordered_by = UserModelChoiceField(queryset=User.objects.all().filter(groups__name='Managers', is_active=1)) class OrderAdmin(admin.ModelAdmin): form = OrderForm My problem: I can't to both of these. If I put in the formfield_for_foreignkey function and add form = OrderForm to use my custom "UserModelChoiceField", it puts the nice name display but it won't select the currently logged in user. I'm new to this, but my guess is that when I use UserModelChoiceField it "erases" the info passed in via formfield_for_foreignkey. Do I need to use the super() function somehow to pass on this info? or something completely different?

    Read the article

  • Django: Filtering datetime field by *only* the year value?

    - by unclaimedbaggage
    Hi folks, I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data comes is below: class Note(models.Model): business = models.ForeignKey(Business) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'client_note' @property def note_year(self): return self.created.strftime('%Y') def __unicode__(self): return '%s' % self.note I've tried a few different ways, but seem to run into hurdles down every path. I'm guessing an effective 'group by' method would do the trick (PostGres DB Backend), but I can't seem to find any Django functionality that supports it. I tried getting individual years from the database but I struggled to find a way of filtering datetime fields by just the year value. Finally, I tried adding the note_year @property but because it's derived, I can't filter those values. Any suggestions for an elegant way to do this? I figure it should be pretty straightforward, but I'm having a heckuva time with it. Any ideas much appreciated.

    Read the article

  • Django admin breaking with non-default primary_key for model with a m2m relationship ?

    - by Gj
    I have a simple Post model with a m2m field to a Tag model. The Tag had for some reason to use a non default primary key. Inside the admin page for a Post, the labels for the multiple selection field for Tags appear, but not the input field itself. I also tried using the filter_horizontal for the tags, but still only the labels appear without the actual field. Any ideas why it breaks and/or workarounds? Thanks!

    Read the article

  • Django query filter a set of data

    - by dana
    if a have a query like following = Relations.objects.filter(initiated_by = request.user) in which i'm having all the users followed by the currently logged in user, and i want to display those user's blog posts. Using a query like: blog = New.objects.filter(created_by = following) it only shows me the blog posts of the user with the id = 1 (though the currently logged in user doesn't actually follow him) in template i have : {% for object in blog %} <a href='/accounts/profile_view/{{object.created_by}}/'> {{object.created_by}}</a> <br /> {{object.post}}<br /> {% endfor %} Where am i wrong?

    Read the article

  • Error in {% markdown %} filter in Django Nonrel

    - by Robert Smith
    I'm having trouble using Markdown in Django Nonrel. I followed this instructions (added 'django.contrib.markup' to INSTALLED_APPS, include {% load markup %} in the template and use |markdown filter after installing python-markdown) but I get the following error: Error in {% markdown %} filter: The Python markdown library isn't installed. In this line: /path/to/project/django/contrib/markup/templatetags/markup.py in markdown they will be silently ignored. """ try: import markdown except ImportError: if settings.DEBUG: raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.") ... return force_unicode(value) else: # markdown.version was first added in 1.6b. The only version of markdown # to fully support extensions before 1.6b was the shortlived 1.6a. if hasattr(markdown, 'version'): extensions = [e for e in arg.split(",") if e] It seems obvious that import markdown is causing the problem but when I run: $ python manage.py shell >>> import elementtree >>> import markdown everthing works alright. Running Markdown 2.0.3, Django 1.3.1, Python 2.7. UPDATE: I thought maybe this was an issue related to permissions, so I changed my project via chmod 777 -R, but it didn't work. Ideas? Thanks!

    Read the article

  • How much knowledge do I need to begin a project in Django

    - by Smock
    I started learning django about a month ago. I have an intermediate C, Java programming experience. I read the first 8 chapters of the django book . Afterwards, I picked up Practical Django Projects by James Bennett and did the first two projects: CMS & Web Blog. Although, I started getting lost when he got to the generic views part. I know that's important but I'm not sure how important that is when trying to implement a project. Anyway, I have a project in mind that I'd like to start; however, I'm nervous as to where to begin. I'm overwhelmed with the number of things that I'd like my project to do but no knowledge or minimal knowledge as to how e.g. how do i implement css and javascript in my project. Moreover, I am aware that some django packages exists to ease development but I don't know if I should use them or not. Anyway, I apologize for my length message. I just want some advice/encouragement. I have a project in mind but do you think I need to read more materials/tutorials or is it smart to just start working on my project based on the minimal knowledge i've gained from those books? Any information that can be provided is much appreciated. I really want to get good at this but I just need some direction.

    Read the article

  • Where to define a filter function for a form field in my Joomla component's preferences

    - by Herman
    I am creating a component in Joomla 2.5. This component has some options that are defined in its config.xml, so they can be set in the preferences of the component. Now I would like to apply a filter to one of these option fields, using the attribute filter="my_filter". In the source code of JForm I saw the following lines at the very end of the implementation of JForm::filterField(): if (strpos($filter, '::') !== false && is_callable(explode('::', $filter))) { $return = call_user_func(explode('::', $filter), $value); } elseif (function_exists($filter)) { $return = call_user_func($filter, $value); } That's what I needed for using a filter function defined by myself! I managed to do this for form fields used in the views of my component. I defined the filter function as MyComponentHelper::my_filter(), where MyComponentHelper is a helper class which I always load in the very base of my component. And in the form's xml I added filter="MyComponentHelper::my_filter" to the fields that have to be filtered. However... when I am trying to apply the filter function to a form field in my component's preferences, I am not in my own component, but in com_config instead, so my helper class is not available! So, therefore, my question: where to define my own filter function in such a way that it can be found and called by JForm::filterField() in com_config?? Help is very much appreciated.

    Read the article

  • Single django instance with subdomains for each app in the django project

    - by jwesonga
    I have a django project (django+apache+mod_wsgi+nginx) with multiple apps, I'd like to map each app as a subdomain: project/ app1 (domain.com) app2 (sub1.domain.com) app3 (sub3.domain.com) I have a single .wsgi script serving the project, which is stored in a folder /apache. Below is my vhost file. I'm using a single vhost file instead of separate ones for each sub-domain: <VirtualHost *:8080> ServerAdmin [email protected] ServerName www.domain.com ServerAlias domain.com DocumentRoot /home/path/to/app/ Alias /admin_media/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media <Directory /home/path/to/wsgi/apache/> Order deny,allow Allow from all </Directory> LogLevel warn ErrorLog /home/path/to/logs/apache_error.log CustomLog /home/path/to/logs/apache_access.log combined WSGIDaemonProcess domain.com user=www-data group=www-data threads=25 WSGIProcessGroup domain.com WSGIScriptAlias / /home/path/to/apache/kcdf.wsgi </VirtualHost> <VirtualHost *:8081> ServerAdmin [email protected] ServerName sub1.domain.com ServerAlias sub1.domain.com DocumentRoot /home/path/to/app Alias /admin_media/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media <Directory /home/path/to/wsgi/apache/> Order deny,allow Allow from all </Directory> LogLevel warn ErrorLog /home/path/to/logs/apache_error.log CustomLog /home/path/to/logs/apache_access.log combined WSGIDaemonProcess sub1.domain.com user=www-data group=www-data threads=25 WSGIProcessGroup sub1.domain.com WSGIScriptAlias / /home/path/to/apache/kcdf.wsgi </VirtualHost> My Nginx configuration for the domain.com: server { listen 80; server_name domain.com; access_log off; error_log off; # proxy to Apache 2 and mod_wsgi location / { proxy_pass http://127.0.0.1:8080/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_max_temp_file_size 0; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } } Configuration for the sub.domain.com: server { listen 80; server_name sub.domain.com; access_log off; error_log off; # proxy to Apache 2 and mod_wsgi location / { proxy_pass http://127.0.0.1:8081/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_max_temp_file_size 0; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } } This set up doesn't seem to work, everything seems to point to the main domain. I've tried http://effbot.org/zone/django-multihost.htm which kind of worked but seems to have issues with loading my css,images,js files.

    Read the article

  • Strange behavior with complex Q object filter queries in Django

    - by HWM-Rocker
    Hi I am trying to write a tagging system for Django, but today I encountered a strange behavior in filter or the Q object (django.db.models.Q). I wrote a function, that converts a search string into a Q object. The next step would be to filter the TaggedObject with these query. But unfortunately I get a strange behavior. when I search (id=20) = Q: (AND: ('tags__tag__id', 20)) and it returns 2 Taged Objects with the ID 1127 and 132 when I search (id=4) = Q: (AND: ('tags__tag__id', 4)) and it returns also 2 Objects, but this time 1180 and 1127 until here is everything fine, but when i make a little bit more complex query like (id=4) or (id=20) = Q: (OR: ('tags__tag__id', 4), ('tags__tag__id', 20)) then it returns 4(!) Objects 1180, 1127, 1127, 132 But the object with the ID 1127 is returned twice, but thats not the behaviour I want. Do I have to live with it, and uniqify that list or can I do something different. The representation of the Q object looks fine for me. But the worst is now, when I search for (id=20) and (id=4) = Q: (AND: ('tags__tag__id', 20), ('tags__tag__id', 4)) then it returns no object at all. But why? The representation should be ok and the object with the id 1127 is tagged by both. What am I missing? Here are also the relevant parts of the classes, that are involved: class TaggedObject(models.Model): """ class that represent a tagged object """ tags = generic.GenericRelation('ObjectTagBridge', blank=True, null=True) class ObjectTagBridge(models.Model): """ Help to connect a generic object to a Tag. """ # pylint: disable-msg=W0232,R0903 content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') tag = models.ForeignKey('Tag') class Tag(models.Model): ... Thanks for your help

    Read the article

  • In Django Combobox choices, how do you lookup description from short value?

    - by MikeN
    In Django models/forms the choices for a combobox often look like this: food_choices = (("",""), ("1", "Falafel"), ("2", "Hummus"), ("3", "Eggplant Stuff, Babaganoush???"), So the value to be stored in the database will be 1/2/3, but the displayed value on the form will be the long description. When we are working in code outside a form, how can we quickly lookup the long description given the short value stored in the model? So I want to map short values to long values: print foo("1") "Falafel"

    Read the article

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