Search Results

Search found 6796 results on 272 pages for 'django templates'.

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

  • Django: common template subsections

    - by Parand
    What's a good way to handle commonly occurring subsections of templates? For example, there is a sub-header section that's used across 4 different pages. The pages are different enough to not work well with template inheritance (ie. "extends" doesn't fit well). Is "include" the recommended method here? It feels a bit heavyweight, requiring each subsection or snippet to be in its own file. Are there any performance issues in using include or is it smart about forming template from the subsections (ie. if I make extensive use of it, do I pay any penalties)? I think what I'm looking for is something like template tags, but without the programming - a simple way to create a library of html template tags I can sprinkle in other templates.

    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

  • Building a template engine - starting point

    - by Anirudh
    We're building a Django-based project with a template component. This component will be separate from the project as such and can be Django/Python, Node, Java or whatever works. The template has to be rendered into HTML. The templates will contain references to objects with properties that are defined in the DB, say, a Bus. For eg, it could be something like [object type="vehicle" weight="heavy"] and it would have to pull a random object from the DB fulfilling the criteria : type="vehicle" weight="heavy" (bus/truck/jet) and then substitute that tag with an image, say, of a Bus. Also it would have to be able to handle some processing. Eg: What is [X type="integer" lte="10"] + [Y type="integer" lte="10"] [option X+Y correct_ans="true"] [option X-Y correct_ans="false"] [option X+y+1 correct_ans="false"] The engine would be expected to fill in a random integer value <= 10 for X and Y and show radioboxes for each of the options. Would also have to store the fact that the first option is the correct answer. Does it to make sense to write something from the scratch? Or is it better to use an existing templating system (like Django's own templating system) as a starting point? Any suggestions on how I can approach this?

    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

  • How to use templated classes as function arguments? (C++)

    - by Keand64
    I have a class declared along the lines of template<int a, int b> class C { public: array[a][b]; } and I want to use it as argument in a function like this: bool DoSomeTests(C &c1, C &c2); but when I compile, it tells me 'use of class template requires template argument list.' I tried template<int a, int b> bool DoSomeTests(C &c1, C &c2); but I get the same error. How can I fix this?

    Read the article

  • Modify Django Forms

    - by Ninefingers
    Hi All, I've recently been developing on the django platform and have stumbled upon Django Forms (forms.Form/forms.ModelForm) as ways of creating <form> html. Now, this is brilliant for quick stuff but what I'm trying to do is a little bit more complicated. Consider a DateField - my current form has fields for day, month and year and constructs a python date object from that. However, a django form creates a single textbox in which the correct format (say 2010-06-15) must be entered. As another example, for large fields I need to replace <input> with <textarea>. I'd like to take advantage of Django's forms for simple validation but I need something simpler for my users. So my question is: can I intercept the rendering of one of these objects to write out the html as I like? If so, do I have to do all the writing myself or can I only do those objects I wish to re-write? Thanks in advance.

    Read the article

  • Django Form Preview

    - by Mark Kecko
    I'm trying to use django's FormPreview and I can't get it to work properly. Here's my code: forms.py class MyForm(forms.ModelForm): status = forms.TypedChoiceField( coerce=int, choices=LIST_STATUS, label="type", widget=forms.RadioSelect ) description = forms.CharField(widget = forms.Textarea) stage = forms.CharField() def __init__(self, useradd=None, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['firm'].label = "Firm" class Meta: model = MyModel fields = ['status', 'description', 'stage'] class MyFormPreview(FormPreview): form_template = 'templates/post.html' preview_template = 'templates/review.html' def process_preview(self, request, cleaned_data): print "processed" def done(self, request, cleaned_data): print "done" # Do something with the cleaned_data, then redirect # to a "success" page. return HttpResponseRedirect('/') urls.py (r'^post/$', MyFormPreview(MyForm)), post.html <form id = "post_ad" action = "" method = "POST" enctype="multipart/form-data"> <table> {{form.as_table}} </table> <input type="submit" name="save" value="Post" /> </form> When I go to /post/ I get the correct form and I fill it out. When I submit the form it goes right back to /post/ but but there are no errors (I've tried displaying {{errors}}) and the form is empty. None of my print statements execute. I'm not sure what I'm missing. Can anyone help me out? I can't find any documentation besides what's on the django site. Also, what's the "preview" variable called that I should use in my preview.html template? {{preview}} or do I just do {{form}} again? -- Answered below. I tried adding 'django.contrib.formtools' to my installed_apps in settings and I tried using the code from the default form templates from django.contrib as suggested below. Still, when I submit the form I go right back to the post template, none of my print statements execute :(

    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

  • Django-South introspection rule doesn't work.

    - by Ory Band
    I'm using Django 1.2.3 and South 0.7.3. I am trying to convert my app (named core) to use Django-South. I have a custom model/field that I'm using, named ImageWithThumbsField. It's basically just the ol' django.db.models.ImageField with some attributes such as height, weight, etc. While trying to ./manage.py convert_to_auth core I receieve South's freezing errors. I have no idea why, I'm Probably missing something... I am using a simple custom Model: from django.db.models import ImageField class ImageWithThumbsField(ImageField): def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, sizes=None, **kwargs): self.verbose_name=verbose_name self.name=name self.width_field=width_field self.height_field=height_field self.sizes = sizes super(ImageField, self).__init__(**kwargs) And this is my introspection rule, which I add to the top of my models.py: from south.modelsinspector import add_introspection_rules from lib.thumbs import ImageWithThumbsField add_introspection_rules( [ ( (ImageWithThumbsField, ), [], { "verbose_name": ["verbose_name", {"default": None}], "name": ["name", {"default": None}], "width_field": ["width_field", {"default": None}], "height_field": ["height_field", {"default": None}], "sizes": ["sizes", {"default": None}], }, ), ], ["^core/.fields/.ImageWithThumbsField",]) This is the errors I receieve: ! Cannot freeze field 'core.additionalmaterialphoto.photo' ! (this field has class lib.thumbs.ImageWithThumbsField) ! Cannot freeze field 'core.material.photo' ! (this field has class lib.thumbs.ImageWithThumbsField) ! Cannot freeze field 'core.material.formulaimage' ! (this field has class lib.thumbs.ImageWithThumbsField) ! South cannot introspect some fields; this is probably because they are custom ! fields. If they worked in 0.6 or below, this is because we have removed the ! models parser (it often broke things). ! To fix this, read http://south.aeracode.org/wiki/MyFieldsDontWork Does anybody know why? What am I doing wrong?

    Read the article

  • Complex derived attributes in Django models

    - by rabidpebble
    What I want to do is implement submission scoring for a site with users voting on the content, much like in e.g. reddit (see the 'hot' function in http://code.reddit.com/browser/sql/functions.sql). My submission model currently keeps track of up and down vote totals. Currently, when a user votes I create and save a related Vote object and then use F() expressions to update the Submission object's voting totals. The problem is that I want to update the score for the submission at the same time, but F() expressions are limited to only simple operations (it's missing support for log(), date_part(), sign() etc.) From my limited experience with Django I can see 4 options here: extend F() somehow (haven't looked at the code yet) to support the missing SQL functions; this is my preferred option and seems to fit within the Django framework the best define a scoring function (much like reddit's 'hot' function) in my database, and have Django use the value of that function for the value of the score field; as far as I can tell, #2 is not possible wrap my two step voting process in a suitably isolated transaction so that I can calculate the voting totals in Python and then update the Submission's voting totals without fear that another vote against the submission could be added/changed in the meantime; I'm hesitant to take this route because it seems overly complex - what is a "suitably isolated transaction" in this case anyway? use raw SQL; I would prefer to avoid this entirely -- what's the point of an ORM if I have to revert to SQL for such a common use case as this! (Note that this coming from somebody who loves sprocs, but is using Django for ease of development.) Before I embark on this mission to extend F() (which I'm not sure is even possible), am I about to reinvent the wheel? Is there a more standard way to do this? It seems like such a common use case and yet in an hour of searching I have yet to find a common solution...

    Read the article

  • Django throws 404 at generic views

    - by x0rg
    I'm trying to get the generic views for a date-based archive working in django. I defined the urls as described in a tutorial, but django returns a 404 error whenever I want to access an url with a variable (such as month or year) in it. It don't even produces a TemplateDoesNotExist-execption. Normal urls without variables work fine. Here's my urlconf: from django.conf.urls.defaults import * from zurichlive.zhl.models import Event info_dict = { 'queryset': Event.objects.all(), 'date_field': 'date', 'allow_future': 'True', } urlpatterns += patterns('django.views.generic.date_based', (r'events/(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_name='archive/detail.html')), (r'^events/(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, template_name='archive/list.html')), (r'^events/(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/$','archive_day',dict(info_dict,template_name='archive/list.html')), (r'^events/(?P<year>d{4})/(?P<month>[a-z]{3})/$','archive_month', dict(info_dict, template_name='archive/list.html')), (r'^events/(?P<year>)/$','archive_year', dict(info_dict, template_name='archive/list.html')), (r'^events/$','archive_index', dict(info_dict, template_name='archive/list.html')), ) When I access /events/2010/may/12/this-is-a-slug I should get to the detail.html template, but instead I get a 404. What am I doing wrong?

    Read the article

  • Komodo Edit 5.2 Django Template Syntax Error - Info: <head> previously mentioned

    - by Lance McNearney
    I am using Komodo Edit 5.2 for editing html and Django template files. It always shows a single syntax error inside the first {% block %} area on the first tag of my template. For example: {% extends "base.html" %} {% load i18n %} {% block title %}Hello{% endblock %} {% block content %} <p>Hello</p> <-- Syntax error on this single line <p>Other lines have no errors</p> {% endblock %} {% block footer %} <p>No errors here</p> {% endblock %} The syntax error given is: Info: <head> previously mentioned I know for a fact that the error has nothing to do with my <head> tag since it occurs in the base template and in child templates (and the IDE isn't smart enough to process the base templates when in a child, etc.) All of my html tags are closed properly and everything validates for XHTML strict. This forum post mentions a similar problem but offers no solution (and may be specific to Smarty syntax highlighting). Any ideas on how to resolve this error (or disable it from being shown)?

    Read the article

  • Django 1.1 template question

    - by Bovril
    Hi All, I'm a little stuck trying to get my head around a django template. I have 2 objects, a cluster and a node I would like a simple page that lists... [Cluster 1] [associated node 1] [associated node 2] [associated node 3] [Cluster 2] [associated node 4] [associated node 5] [associated node 6] I've been using Django for about 2 days so if i've missed the point, please be gentle :) Models - class Node(models.Model): name = models.CharField(max_length=30) description = models.TextField() cluster = models.ForeignKey(Cluster) def __unicode__(self): return self.name class Cluster(models.Model): name = models.CharField(max_length=30) description = models.TextField() def __unicode__(self): return self.name Views - def DSAList(request): clusterlist = Cluster.objects.all() nodelist = Node.objects.all() t = loader.get_template('dsalist.html') v = Context({ 'CLUSTERLIST' : clusterlist, 'NODELIST' : nodelist, }) return HttpResponse(t.render(v)) Template - <body> <TABLE> {% for cluster in CLUSTERLIST %} <tr> <TD>{{ cluster.name }}</TD> {% for node in NODELIST %} {% if node.cluster.id == cluster.id %} <tr> <TD>{{ node.name }}</TD> </tr> {% endif %} {% endfor %} </tr> {% endfor %} </TABLE> </body> Any ideas ?

    Read the article

  • Django, url tag in template doesn't work: NoReverseMatch

    - by Lukasz Jocz
    I've encountered a problem with generating reverse url in templates in django. I'm trying to solve it since a few hours and I have no idea what the problem might be. URL reversing works great in models and views: # like this in models.py @models.permalink def get_absolute_url(self): return ('entry', (), { 'entry_id': self.entry.id, }) # or this in views.py return HttpResponseRedirect(reverse('entry',args=(entry_id,))) but when I'm trying to make it in template I get such an error: NoReverseMatch at /entry/1/ Reverse for ''add_comment'' with arguments '(1L,)' and keyword arguments '{}' not found. My file structure looks like this: project/ +-- frontend ¦   +-- models.py ¦   +-- urls.py ¦   +-- views.py +-- settings.py +-- templates ¦   +-- add_comment.html ¦   +-- entry.html +-- utils ¦   +-- with_template.py +-- wsgi.py My urls.py: from project.frontend.views import * from django.conf.urls import patterns, include, url urlpatterns = patterns('project.frontend.views', url(r'^entry/(?P<entry_id>\d+)/', 'entry', name="entry"), (r'^entry_list/', 'entry_list'), Then entry_list.html: {% extends "base.html" %} {% block content %} {% for entry in entries %} {% url 'entry' entry.id %} {% endfor %} {% endblock %} In views.py I have: @with_template def entry(request, entry_id): entry = Entry.objects.get(id=entry_id) entry.comments = entry.get_comments() return locals() where with_template is following decorator(but I don't think this is a case): class TheWrapper(object): def __init__(self, default_template_name): self.default_template_name = default_template_name def __call__(self, func): def decorated_func(request, *args, **kwargs): extra_context = kwargs.pop('extra_context', {}) dictionary = {} ret = func(request, *args, **kwargs) if isinstance(ret, HttpResponse): return ret dictionary.update(ret) dictionary.update(extra_context) return render_to_response(dictionary.get('template_name', self.default_template_name), context_instance=RequestContext(request), dictionary=dictionary) update_wrapper(decorated_func, func) return decorated_func if not callable(arg): return TheWrapper(arg) else: default_template_name = ''.join([ arg.__name__, '.html']) return TheWrapper(default_template_name)(arg) Do you have any idea, what may cause the problem? Great thanks in advance!

    Read the article

  • Cannot get MEDIA_URL from Django widget's template

    - by Eric
    Hi folks, I am a new Djangoer, and figuring out how to build custom widget, my problem is cannot get the MEDIA_URL in my widget's template, while the form use MySelectWidget able to get the MEDIA_URL itself. # #plus_sign.html # <a href="" class="" id="id_{{ field }}"> <img src="{{ MEDIA_URL }}images/plus_sign.gif" width="10" height="10" alt="Add"/> </a> *^ cannot load the {{ MEDIA_URL}} to this widget's template, and therefore I can't load the .gif image properly. :(* # #custom_widgets.py # from django import forms class MySelectMultiple(forms.SelectMultiple): def render(self, name, *args, **kwargs): html = super(MySelectMultiple, self).render(name, *args, **kwargs) plus = render_to_string("plus_sign.html", {'field': name}) return html+plus # #forms.py # from django import forms from myapp.custom_widgets.py import MySelectMultiple class MyForm(forms.ModelForm): contacts = forms.ModelMultipleChoiceField(Contact.objects, required=False, widget=MySelectMultiple) # #views.py # def AddContacts(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data new = form.save() return HttpResponseRedirect('/addedContact/') else: form = MyForm() return render_to_response('shop/my_form.html', {'form': form}, context_instance=RequestContext(request)) # #my_form.html # {% extends "base.html" %} {% block content %} {{ form.contacts }} {% endblock %} Please let me know how can I load the widget's image properly. Thank you so much for all responses.

    Read the article

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