Search Results

Search found 8719 results on 349 pages for 'django views'.

Page 4/349 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Django TemplateSyntaxError only on live server (templates exist)

    - by Tom
    I'm getting a strange error that only occurs on the live server. My Django templates directory is set up like so base.html two-column-base.html portfolio index.html extranet base.html index.html The portfolio pages work correctly locally on multiple machines. They inherit from either the root base.html or two-column-base.html. However, now that I've posted them to the live box (local machines are Windows, live is Linux), I get a TemplateSyntaxError: "Caught TemplateDoesNotExist while rendering: base.html" when I try to load any portfolio pages. It seems to be a case where the extends tag won't work in that root directory (???). Even if I do a direct_to_template on two-column-base.html (which extends base.html), I get that error. The extranet pages all work perfectly, but those templates all live inside the /extranet folder and inherit from /extranet/base.html. Possible issues I've checked: file permissions on the server are fine the template directory is correct on the live box (I'm using os.path.dirname(os.path.realpath(__file__)) to make things work across machines) files exist and the /templates directories exactly match my local copy removing the {% extends %} block from the top of any broken template causes the templates to render without a problem manually starting a shell session and calling get_template on any of the files works, but trying to render it blows up with the same exception on any of the extended templates. Doing the same with base.html, it renders perfectly (base.html also renders via direct_to_template) Django 1.2, Python 2.6 on Webfaction. Apologies in advance because this is my 3rd or 4th "I'm doing something stupid" question in a row. The only x-factor I can think of is this is my first time using Mercurial instead ofsvn. Not sure how I could have messed things up via that. EDIT: One possible source of problems: local machine is Python 2.5, live is 2.6. Here's a traceback of me trying to render 'two-column-base.html', which extends 'base.html'. Both files are in the same directory, so if it can find the first, it can find the second. c is just an empty Context object. >>> render_to_string('two-column-base.html', c) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader.py", line 186, in render_to_string return t.render(context_instance) File "/home/lightfin/webapps/django/lib/python2.6/django/template/__init__.py", line 173, in render return self._render(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/__init__.py", line 167, in _render return self.nodelist.render(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/__init__.py", line 796, in render bits.append(self.render_node(node, context)) File "/home/lightfin/webapps/django/lib/python2.6/django/template/debug.py", line 72, in render_node result = node.render(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader_tags.py", line 103, in render compiled_parent = self.get_parent(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader_tags.py", line 100, in get_parent return get_template(parent) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader.py", line 157, in get_template template, origin = find_template(template_name) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader.py", line 138, in find_template raise TemplateDoesNotExist(name) TemplateSyntaxError: Caught TemplateDoesNotExist while rendering: base.html I'm wondering if this is somehow related to the template caching that was just added to Django. EDIT 2 (per lazerscience): template-related settings: import os PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates'), ) sample view: def project_list(request, jobs, extra_context={}): context = { 'jobs': jobs, } print context context.update(extra_context) return render_to_response('portfolio/index.html', context, context_instance=RequestContext(request)) The templates in reverse-order are: http://thosecleverkids.com/junk/index.html http://thosecleverkids.com/junk/portfolio-base.html http://thosecleverkids.com/junk/two-column-base.html http://thosecleverkids.com/junk/base.html though in the real project the first two live in a directory called "portfolio".

    Read the article

  • Django models query

    - by Hulk
    Code: class criteria(models.Model): details = models.CharField(max_length = 512) Headerid = models.ForeignKey(Header) def __unicode__(self): return self.id() the details corresponds to a textarea in the UI and a validation is done for 512 characters but when this is saved. /home/project/django/django/core/handlers/base.py in get_response, line 109 Is this any thing related with schema or number of characters entered from UI

    Read the article

  • Django: Generating a queryset from a GET request

    - by Nimmy Lebby
    I have a Django form setup using GET method. Each value corresponds to attributes of a Django model. What would be the most elegant way to generate the query? Currently this is what I do in the view: def search_items(request): if 'search_name' in request.GET: query_attributes = {} query_attributes['color'] = request.GET.get('color', '') if not query_attributes['color']: del query_attributes['color'] query_attributes['shape'] = request.GET.get('shape', '') if not query_attributes['shape']: del query_attributes['shape'] items = Items.objects.filter(**query_attributes) But I'm pretty sure there's a better way to go about it.

    Read the article

  • Odd behavior in Django Form (readonly field/widget)

    - by jamida
    I'm having a problem with a test app I'm writing to verify some Django functionality. The test app is a small "grade book" application that is currently using Alex Gaynor's readonly field functionality http://lazypython.blogspot.com/2008/12/building-read-only-field-in-django.html There are 2 problems which may be related. First, when I flop the comment on these 2 lines below: # myform = GradeForm(data=request.POST, instance=mygrade) myform = GradeROForm(data=request.POST, instance=mygrade) it works like I expect, except of course that the student field is changeable. When the comments are the shown way, the "studentId" field is displayed as a number (not the name, problem 1) and when I hit submit I get an error saying that studentId needs to be a Student instance. I'm at a loss as to how to fix this. I'm not wedded to Alex Gaynor's code. ANY code will work. I'm relatively new to both Python and Django, so the hints I've seen on websites that say "making a read-only field is easy" are still beyond me. // models.py class Student(models.Model): name = models.CharField(max_length=50) parent = models.CharField(max_length=50) def __unicode__(self): return self.name class Grade(models.Model): studentId = models.ForeignKey(Student) finalGrade = models.CharField(max_length=3) # testbed.grades.readonly is alex gaynor's code from testbed.grades.readonly import ReadOnlyField class GradeROForm(ModelForm): studentId = ReadOnlyField() class Meta: model=Grade class GradeForm(ModelForm): class Meta: model=Grade // views.py def modifyGrade(request,student): student = Student.objects.get(name=student) mygrade = Grade.objects.get(studentId=student) if request.method == "POST": # myform = GradeForm(data=request.POST, instance=mygrade) myform = GradeROForm(data=request.POST, instance=mygrade) if myform.is_valid(): grade = myform.save() info = "successfully updated %s" % grade.studentId else: # myform=GradeForm(instance=mygrade) myform=GradeROForm(instance=mygrade) return render_to_response('grades/modifyGrade.html',locals()) // template <p>{{ info }}</p> <form method="POST" action=""> <table> {{ myform.as_table }} </table> <input type="submit" value="Submit"> </form> // Alex Gaynor's code from django import forms from django.utils.html import escape from django.utils.safestring import mark_safe from django.forms.util import flatatt class ReadOnlyWidget(forms.Widget): def render(self, name, value, attrs): final_attrs = self.build_attrs(attrs, name=name) if hasattr(self, 'initial'): value = self.initial return mark_safe("<span %s>%s</span>" % (flatatt(final_attrs), escape(value) or '')) def _has_changed(self, initial, data): return False class ReadOnlyField(forms.FileField): widget = ReadOnlyWidget def __init__(self, widget=None, label=None, initial=None, help_text=None): forms.Field.__init__(self, label=label, initial=initial, help_text=help_text, widget=widget) def clean(self, value, initial): self.widget.initial = initial return initial

    Read the article

  • What is causing this OverflowError in Django?

    - by orokusaki
    I'm using a normal ModelForm.save() to create an object, and this exception comes up. It worked fine before until I added commit_manually, transaction.rollback() and transaction.commit() to my view. Has anyone else ran into this? Is this because of sqlite3? OverflowError: long too big to convert C:\Python26\Lib\site-packages\django-trunk\django\db\backends\sqlite3\base.py in execute, line 197 params: (203866156270872165269663274649746494334L,) query: u'SELECT (1) AS "a", "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = ? LIMIT 1' self <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x015D5A98> Why would that L param be passed in, and

    Read the article

  • Django - provide additional information in template

    - by Ninefingers
    Hi all, I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing additional information about the link, such as what the address type is to the that contact (home, work etc). What I'm trying to do is pass this information out to a view, so in my full view of a contact I can do this: def contact_view_full(request, contact_id): c = get_object_or_404(Contact, id=contact_id) a = [] links = ContactAddressLink.objects.filter(ContactID=c.id) for link in links: b = Address.objects.get(id=link.AddressID_id) a.append(b) return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request)) And so I can do the equivalent of c.Addresses.all() or however the ManyToManyField works. What I'm interested to know is how can I pass out information about the link in the link object with the 'addresses' : a information, so that when my template does this: {% for address in addresses %} <!-- ... --> {% endfor %} and properly associate the correct link object data with the address. So what's the best way to achieve this? I'm thinking a union of two objects might be an idea but I haven't enough experience with Django to know if that's considered the best way of doing it. Suggestions? Thanks in advance. Nf

    Read the article

  • Simple Observation in Django: How Can I Correctly Modify The `attrs` sent to __new__ of a Django Mod

    - by DGGenuine
    Hello, I'm a strong proponent of the observer pattern, and this is what I'd like to be able to do in my Django models.py: class AModel(Model): __metaclass__ = SomethingMagical @post_save(AnotherModel) @classmethod def observe_another_model_saved(klass, sender, instance, created, **kwargs): pass @pre_init('YetAnotherModel') @classmethod def observe_yet_another_model_initializing(klass, sender, *args, **kwargs): pass @post_delete('DifferentApp.SomeModel') @classmethod def observe_some_model_deleted(klass, sender, **kwargs): pass This would connect a signal with sender = the decorator's argument and receiver = the decorated method. Right now my signal connection code all exists in __init__.py which is okay, but a little unmaintainable. I want this code all in one place, the models.py file. Thanks to helpful feedback from the community I'm very close (I think.) (I'm using a metaclass solution instead of the class decorator solution in the previous question/answer because you can't set attributes on classmethods, which I need.) I am having a strange error I don't understand. At the end of my post are the contents of a models.py that you can pop into a fresh project/application to see the error. Set your database to sqlite and add the application to installed apps. This is the error: Validating models... Unhandled exception in thread started by Traceback (most recent call last): File "/Library/Python/2.6/site-packages//lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 253, in validate raise CommandError("One or more models did not validate:\n%s" % error_text) django.core.management.base.CommandError: One or more models did not validate: local.myothermodel: 'my_model' has a relation with model MyModel, which has either not been installed or is abstract. I've indicated a few different things you can comment in/out to fix the error. First, if you don't modify the attrs sent to the metaclass's __new__, then the error does not arise. (Note even if you copy the dictionary element by element into a new dictionary, it still fails; only using the exact attrs dictionary works.) Second, if you reference the first model by class rather than by string, the error also doesn't arise regardless of what you do in __new__. I appreciate your help. I'll be githubbing the solution if and when it works. Maybe other people would enjoy a simplified way to use Django signals to observe application happenings. #models.py from django.db import models from django.db.models.base import ModelBase from django.db.models import signals import pdb class UnconnectedMethodWrapper(object): sender = None method = None signal = None def __init__(self, signal, sender, method): self.signal = signal self.sender = sender self.method = method def post_save(sender): return _make_decorator(signals.post_save, sender) def _make_decorator(signal, sender): def decorator(view): return UnconnectedMethodWrapper(signal, sender, view) return decorator class ConnectableModel(ModelBase): """ A meta class for any class that will have static or class methods that need to be connected to signals. """ def __new__(cls, name, bases, attrs): unconnecteds = {} ## NO WORK newattrs = {} for name, attr in attrs.iteritems(): if isinstance(attr, UnconnectedMethodWrapper): unconnecteds[name] = attr newattrs[name] = attr.method #replace the UnconnectedMethodWrapper with the method it wrapped. else: newattrs[name] = attr ## NO WORK # newattrs = {} # for name, attr in attrs.iteritems(): # newattrs[name] = attr ## WORKS # newattrs = attrs new = super(ConnectableModel, cls).__new__(cls, name, bases, newattrs) for name, unconnected in unconnecteds.iteritems(): _connect_signal(unconnected.signal, unconnected.sender, getattr(new, name), new._meta.app_label) return new def _connect_signal(signal, sender, receiver, default_app_label): # full implementation also accepts basestring as sender and will look up model accordingly signal.connect(sender=sender, receiver=receiver) class MyModel(models.Model): __metaclass__ = ConnectableModel @post_save('In my application this string matters') @classmethod def observe_it(klass, sender, instance, created, **kwargs): pass @classmethod def normal_class_method(klass): pass class MyOtherModel(models.Model): ## WORKS # my_model = models.ForeignKey(MyModel) ## NO WORK my_model = models.ForeignKey('MyModel')

    Read the article

  • int() error in django views

    - by Hulk
    def displaydata(request): response_dict = {} offset = int(request.GET.get('iDisplayStart')) There is an error as, int() argument must be a string or a number at the above said line (i.e,`request.GET.get('iDisplayStart')) And in the template code, $(document).ready(function() { $.ajaxSetup({ cache: false }); oTable = $('#qp_table').dataTable( { "aoColumns": [ {"sWidth": "5%" }, {"sWidth": "35%" }, {"sWidth": "27%" }, {"sWidth": "15%"}, { "bSortable": false, "sWidth": "0%"}, {"bSortable": false, "sWidth": "0%"} ], "aaSorting": [[0, 'asc']], "bProcessing": true, "bServerSide": true, "sAjaxSource": "/diaplaydata/", "bJQueryUI": true, "sPaginationType": "full_numbers", "bFilter": false, "oLanguage" : { "sZeroRecords": "No data found", "sProcessing" : "Fetching Data" } });

    Read the article

  • Django: Summing values of records grouped by foreign key

    - by Dan0
    Hi there In django, given the following models (slightly simplified), I'm struggling to work out how I would get a view including sums of groups class Client(models.Model): api_key = models.CharField(unique=True, max_length=250, primary_key=True) name = models.CharField(unique=True, max_length=250) class Purchase(models.Model): purchase_date = models.DateTimeField() client = models.ForeignKey(SavedClient, to_field='api_key') amount_to_invoice = models.FloatField(null=True) For a given month, I'd like to see e.g. April 2010 For Each Client that purchased this month: * CLient: Name * Total amount of Purchases for this month * Total cost of purchases for this month For each Purchase made by client: * Date * Amount * Etc I've been looking into django annotation, but can't get my head around how to sum values of a field for a particular group over a particular month and send the information to a template as a variable/tag. Any info would be appreciated

    Read the article

  • django auth : strange error with authenticate()

    - by Rohit
    I am using authenticate() to authenticating users manually. Using admin interface I can see that there is no 'last_login' attribute for Users Debug traceback is : Environment: Request Method: GET Request URL: https://localhost/login/ Django Version: 1.1.1 Python Version: 2.6.5 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'mobius.polls'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/usr/lib/pymodules/python2.6/django/contrib/auth/__init__.py" in login 55. user.last_login = datetime.datetime.now() Exception Type: AttributeError at /login/ Exception Value: 'unicode' object has no attribute 'last_login' I cant figure out, why is there this discrepancy. Any kind of help would be appreciated. Thanks in advance!

    Read the article

  • Installing Django on Shared Server: No module named MySQLdb?

    - by Mark
    I'm getting this error Traceback (most recent call last): File "/home/<username>/flup/server/fcgi_base.py", line 558, in run File "/home/<username>/flup/server/fcgi_base.py", line 1116, in handler File "/home/<username>/python/django/django/core/handlers/wsgi.py", line 241, in __call__ response = self.get_response(request) File "/home/<username>/python/django/django/core/handlers/base.py", line 73, in get_response response = middleware_method(request) File "/home/<username>/python/django/django/contrib/sessions/middleware.py", line 10, in process_request engine = import_module(settings.SESSION_ENGINE) File "/home/<username>/python/django/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/<username>/python/django/django/contrib/sessions/backends/db.py", line 2, in ? from django.contrib.sessions.models import Session File "/home/<username>/python/django/django/contrib/sessions/models.py", line 4, in ? from django.db import models File "/home/<username>/python/django/django/db/__init__.py", line 41, in ? backend = load_backend(settings.DATABASE_ENGINE) File "/home/<username>/python/django/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/home/<username>/python/django/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/<username>/python/django/django/db/backends/mysql/base.py", line 13, in ? raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb when I try to run this script on my shared server #!/usr/bin/python import sys, os sys.path.insert(0, "/home/<username>/python/django") sys.path.insert(0, "/home/<username>/python/django/www") # projects directory os.chdir("/home/<username>/python/django/www/<project>") os.environ['DJANGO_SETTINGS_MODULE'] = "<project>.settings" from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false") But, my web host just installed MySQLdb for me a few hours ago. When I run python from the shell I can import MySQLdb just fine. Why would this script report that it can't find it?

    Read the article

  • Django deployment - can't import app.urls

    - by hora
    I just moved a django project to a deployment server from my dev server, and I'm having some issues deploying it. My apache config is as follows: <Location "/"> Order allow,deny Allow from all SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE project.settings PythonDebug On PythonPath "['/home/django/'] + sys.path" </Location> Django does work, since it renders the Django debug views, but I get the following error: ImportError at / No module named app.urls And here is all the information Django gives me: Request Method: GET Request URL: http://myserver.com/ Django Version: 1.1.1 Python Version: 2.6.5 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.admindocs', 'project.app'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/usr/lib64/python2.6/site-packages/django/core/handlers/base.py" in get_response 83. request.path_info) File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in resolve 218. sub_match = pattern.resolve(new_path) File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in resolve 216. for pattern in self.url_patterns: File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in _get_url_patterns 245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/lib64/python2.6/site-packages/django/core/urlresolvers.py" in _get_urlconf_module 240. self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib64/python2.6/site-packages/django/utils/importlib.py" in import_module 35. __import__(name) Exception Type: ImportError at / Exception Value: No module named app.urls Any ideas as to why I get an import error?

    Read the article

  • Django "comment_was_flagged" signal

    - by tsoporan
    Hello, This is my first time working with django signals and I would like to hook the "comment_was_flagged" signal provided by the comments app to notify me when a comment is flagged. This is my code, but it doesn't seem to work, am I missing something? from django.contrib.comments.signals import comment_was_flagged from django.core.mail import send_mail def comment_flagged_notification(sender, **kwargs): send_mail('testing moderation', 'testing', 'test@localhost', ['[email protected]',]) comment_was_flagged.connect(comment_flagged_notification) (I am just testing the email for now, but I have assured the email is sending properly.) Thanks!

    Read the article

  • Django JSON serializable error

    - by Hulk
    With the following code below, There is an error saying File "/home/user/web_pro/info/views.py", line 184, in headerview, raise TypeError("%r is not JSON serializable" % (o,)) TypeError: <lastname: jerry> is not JSON serializable In the models code header(models.Model): firstname = models.ForeignKey(Firstname) lastname = models.ForeignKey(Lastname) In the views code headerview(request): header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit] l_array = [] l_array_obj = [] for obj in header: l_array_obj = [obj.title, obj.lastname ,obj.firstname ] l_array.append(l_array_obj) dictionary_l.update({'Data': l_array}) ; return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript') what is this error and how to resolve this? thanks..

    Read the article

  • django-multilingual and switching between languages on template side

    - by israkir
    I am trying to use django-multilingual and setup it properly. But what I found is that everything is clear for django-multilingual except a template usage example. I just started to use django and I don't know, maybe because of this reason, I cannot figure out how to switch between languages on template side. Is there any example that you can give or any 'more' clear source/documentation about this?

    Read the article

  • Edit/show Primary Key in Django Admin

    - by emcee
    It appears Django hides fields that are flagged Primary Key from being displayed/edited in the Django admin interface. Let's say I'd like to input data in which I may or may not want to specify a primary key. How would I go about displaying primary keys in Django-admin, and how could I make specifying it optional? Many thanks in advance, beloved hive-mind.

    Read the article

  • Django Admin Actions missing

    - by Andrew C
    One of my Django sites is missing the Django Admin Action bar shown here: http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#ref-contrib-admin-actions There is no checkbox next to each row and no Action select box near the top of the page. This is happening on every model. I have several sites running Django 1.1, and they all show the Admin Actions, so it feels like a local configuration issue. Anyone seen this before?

    Read the article

  • Invalidating Memcached Keys on save() in Django

    - by Zack
    I've got a view in Django that uses memcached to cache data for the more highly trafficked views that rely on a relatively static set of data. The key word is relatively: I need invalidate the memcached key for that particular URL's data when it's changed in the database. To be as clear as possible, here's the meat an' potatoes of the view (Person is a model, cache is django.core.cache.cache): def person_detail(request, slug): if request.is_ajax(): cache_key = "%s_ABOUT_%s" % settings.SITE_PREFIX, slug # Check the cache to see if we've already got this result made. json_dict = cache.get(cache_key) # Was it a cache hit? if json_dict is None: # That's a negative Ghost Rider person = get_object_or_404(Person, display = True, slug = slug) json_dict = { 'name' : person.name, 'bio' : person.bio_html, 'image' : person.image.extra_thumbnails['large'].absolute_url, } cache.set(cache_key) # json_dict will now exist, whether it's from the cache or not response = HttpResponse() response['Content-Type'] = 'text/javascript' response.write(simpljson.dumps(json_dict)) # Make sure it's all properly formatted for JS by using simplejson return response else: # This is where the fully templated response is generated What I want to do is get at that cache_key variable in it's "unformatted" form, but I'm not sure how to do this--if it can be done at all. Just in case there's already something to do this, here's what I want to do with it (this is from the Person model's hypothetical save method) def save(self): # If this is an update, the key will be cached, otherwise it won't, let's see if we can't find me try: old_self = Person.objects.get(pk=self.id) cache_key = # Voodoo magic to get that variable old_key = cache_key.format(settings.SITE_PREFIX, old_self.slug) # Generate the key currently cached cache.delete(old_key) # Hit it with both barrels of rock salt # Turns out this doesn't already exist, let's make that first request even faster by making this cache right now except DoesNotExist: # I haven't gotten to this yet. super(Person, self).save() I'm thinking about making a view class for this sorta stuff, and having functions in it like remove_cache or generate_cache since I do this sorta stuff a lot. Would that be a better idea? If so, how would I call the views in the URLconf if they're in a class?

    Read the article

  • Math on Django Templates

    - by Leandro Abilio
    Here's another question about Django. I have this code: views.py cursor = connections['cdr'].cursor() calls = cursor.execute("SELECT * FROM cdr where calldate > '%s'" %(start_date)) result = [SQLRow(cursor, r) for r in cursor.fetchall()] return render_to_response("cdr_user.html", {'calls':result }, context_instance=RequestContext(request)) I use a MySQL query like that because the database is not part of a django project. My cdr table has a field called duration, I need to divide that by 60 and multiply the result by a float number like 0.16. Is there a way to multiply this values using the template tags? If not, is there a good way to do it in my views? My template is like this: {% for call in calls %} <tr class="{% cycle 'odd' 'even' %}"><h3> <td valign="middle" align="center"><h3>{{ call.calldate }}</h3></td> <td valign="middle" align="center"><h3>{{ call.disposition }}</h3></td> <td valign="middle" align="center"><h3>{{ call.dst }}</h3></td> <td valign="middle" align="center"><h3>{{ call.billsec }}</h3></td> <td valign="middle" align="center">{{ (call.billsec/60)*0.16 }}</td></h3> </tr> {% endfor %} The last is where I need to show the value, I know the "(call.billsec/60)*0.16" is impossible to be done there. I wrote it just to represent what I need to show.

    Read the article

  • Django authentication in django nonrel on GAE

    - by tooba
    I'm using the Django nonrel project on a google app engine project running locally in development. I've created my own models and these are fine when they are saved and retrieved in the datastore. I'm hoping to use django.contrib.auth to provide the user functionality. I can use the shell to create users and these get assigned an ID. When I create one of my own models which references User I have to pass in a user ID as it quite rightly fails otherwise. However, checking via the gae admin interface I can't see the User model in the datastore for the users I've created via the shell. Nor can I retreive the user details from one of my models which references them. Calls to mymodel.user.username return nothing. Nor can I log into admin using the username and password I've set up. I can see saved versions of the models I've made in the gae admin app. I get the impression that users are being created somewhere other than the datastore. Is there something else I need to do to use the standard contrib.auth users with django-nonrel and gae?

    Read the article

  • Django url parameters

    - by Hulk
    How to pass two paramters in urls in django <script> url=/toolbox/display/" + id + "2"; window.location=url; </script> Also how is this handeled in urls.py (r'^display/(?P<rid>\d+)/(?P<param>\d+)/$', 'table_display'), In views, def table_display(request,rid,param): print param //This should print 2

    Read the article

  • Django template-printing variables

    - by Hulk
    In django views def add(request): dict{} co_data = optarr dict.update({'co_data' : co_data}) logging.debug(co_data) return render_to_response('scheme/create.html',context_instance=RequestContext(request,{'dict': dict})) And data has the following string 1##2##3##4## And in the template when i say {{co_data}} it doesnt display the values.Please point out whats wrong in the code. Thanks..

    Read the article

  • How to make custom join query with Django ?

    - by xRobot
    I have these 2 models: genre = ( ('D', 'Dramatic'), ('T', 'Thriller'), ('L', 'Love'), ) class Book(models.Model): title = models.CharField(max_length=100) genre = models.CharField(max_length=1, choices=genre) class Author(models.Model): user = models.ForeignKey(User, unique=True) born = models.DateTimeField('born') book = models.ForeignKey(Book) I need to retrieve first_name and last_name of all authors of dramatic's books. How can I do this in django ?

    Read the article

  • Accessing django choice field

    - by Hulk
    there is a module as header , from test.models import SEL_VALUES class rubrics_header(models.Model): sel_values = models.IntegerField(choices=SEL_VALUES) So when SEL_VALUES is imported from test.modules.What is the code that has to go in views to get the choices in sel_values . And the test.modules has the following, class SEL_VALUES: vaue = 0 value2 = 1 class Entries(forms.Form) : models.IntegerField(choices=SEL_VALUES) SEL_VALUES = ((ACCESS.value,'NAME'),(ACCESS.value2,'DESIGNATION'))

    Read the article

  • Django foreign key error

    - by Hulk
    In models the code is as, class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.ForeignKey(header) def __unicode__(self): return self.id() In views, p_l=header.objects.filter(id=rid) for rows in row_data: row_query =criteria(details=rows,headerid=p_l) row_query.save() In row_query =criteria(details=rows,headerid=p_l) there is an error saying 'long' object is not callable in models.py in __unicode__, What is wrong in the code Thanks..

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >