Search Results

Search found 23428 results on 938 pages for 'django related manager'.

Page 9/938 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Are Django template tags cached?

    - by thebossman
    I have gone through the (painful) process of writing a custom template tag for use in Django. It is registered as an inclusion_tag so that it renders a template. However, this tag breaks as soon as I try to change something. I've tried changing the number of parameters and correspondingly changing the parameters when it's called. It's clear the new tag code isn't being loaded, because an error is thrown stating that there is a mismatch in the number of parameters, and it's evident that it's attempting to call the old function. The same problem occurs if I try to change the name of the template being rendered and correspondingly change the name of the template on disk. It continues to try to call the old template. I've tried clearing old .pyc files with no luck. Overall, the system is acting as though it's caching the template tags, likely due to the register command. I have dug through endless threads trying to find out if this is so, but all could find it James Bennett stating here that register doesn't do anything. Please help!

    Read the article

  • Django DRY Feeds

    - by Mandx
    I'm using the Django Feeds Framework and it's really nice, very intuitive and easy to use. But, I think there is a problem when creating links to feeds in HTML. For example: <link rel="alternate" type="application/rss+xml" title="{{ feed_title }}" href="{{ url_of_feed }}" /> Link's HREF attribute can be easily found out, just use reverse() But, what about the TITLE attribute? Where the template engine should look for this? Even more, what if the feed is build up dinamically and the title depends on parameters (like this)? I can't come up with a solution that "seems" DRY to me... All that I can come up with is using context processors o template tags, but it gets messy when the context procesor/template tag has to find parameters to construct the Feed class, and writing this I realize I don't even know how to create a Feed instance myself within the view. If I put all this logic in the view, it would not be just one view. Also, the value for TITLE would be in the view AND in the feed.

    Read the article

  • Django Querying Relation of Relation

    - by Brent
    I'm stuck on a Django ORM issue that is bugging me. I have a set of models linked by a foreign key but the requirements are a bit odd. I need to list items by their relation's relation. This is hard to explain so I've tried to depict this below, given: Work ManyToMany(Award) Award ForeignKey(AwardCategory) AwardCategory I need to list work items so they are listed by the award category. Desired output would be: Work Instance A Award Instance A that belongs to Award Category Instance A Award Instance C that belongs to Award Category Instance A Award Instance G that belongs to Award Category Instance A Work Instance A (same instance as above, but listed by different award__category) Award Instance F that belongs to Award Category Instance B Award Instance R that belongs to Award Category Instance B Award Instance Z that belongs to Award Category Instance B Work Instance B Award Instance B that belongs to Award Category Instance A Award Instance A that belongs to Award Category Instance A Essentially I want to list all work by the award category. I can get this to work in part but my solution is filthy and gross. I'm wondering if there is a better way. I considered using a ManyToMany and a through attribute but I'm not certain if I'm utilizing it correctly.

    Read the article

  • Add fields to Django ModelForm that aren't in the model

    - by Cyclic
    I have a model that looks like: class MySchedule(models.Model): start_datetime=models.DateTimeField() name=models.CharField('Name',max_length=75) With it comes its ModelForm: class MyScheduleForm(forms.ModelForm): startdate=forms.DateField() starthour=forms.ChoiceField(choices=((6,"6am"),(7,"7am"),(8,"8am"),(9,"9am"),(10,"10am"),(11,"11am"), (12,"noon"),(13,"1pm"),(14,"2pm"),(15,"3pm"),(16,"4pm"),(17,"5pm"), (18,"6pm" startminute=forms.ChoiceField(choices=((0,":00"),(15,":15"),(30,":30"),(45,":45")))),(19,"7pm"),(20,"8pm"),(21,"9pm"),(22,"10pm"),(23,"11pm"))) class Meta: model=MySchedule def clean(self): starttime=time(int(self.cleaned_data.get('starthour')),int(self.cleaned_data.get('startminute'))) return self.cleaned_data try: self.instance.start_datetime=datetime.combine(self.cleaned_data.get("startdate"),starttime) except TypeError: raise forms.ValidationError("There's a problem with your start or end date") Basically, I'm trying to break the DateTime field in the model into 3 more easily usable form fields -- a date picker, an hour dropdown, and a minute dropdown. Then, once I've gotten the three inputs, I reassemble them into a DateTime and save it to the model. A few questions: 1) Is this totally the wrong way to go about doing it? I don't want to create fields in the model for hours, minutes, etc, since that's all basically just intermediary data, so I'd like a way to break the DateTime field into sub-fields. 2) The difficulty I'm running into is when the startdate field is blank -- it seems like it never gets checked for non-blankness, and just ends up throwing up a TypeError later when the program expects a date and gets None. Where does Django check for blank inputs, and raise the error that eventually goes back to the form? Is this my responsibility? If so, how do I do it, since it doesn't evaluate clean_startdate() since startdate isn't in the model. 3) Is there some better way to do this with inheritance? Perhaps inherit the MyScheduleForm in BetterScheduleForm and add the fields there? How would I do this? (I've been playing around with it for over an hours and can't seem to get it) Thanks! [Edit:] Left off the return self.cleaned_data -- lost it in the copy/paste originally

    Read the article

  • user inheritance in django

    - by amateur
    Hi guys, I saw a couple of ways extending user information of users and decided to adopt the model inheritance method. for instance, I have : class Parent(User): contact_means = models.IntegerField() is_staff = False objects = userManager() Now it is done, I've downloaded django_registration to help me out with sending emails to new users. The thing is, instead of using registration forms to register new user, I want to to invoke the email sending/acitvation capability of django_registration. So my workflow is: 1. add new Parent object in admin page. 2. send email My problem is, the django-registration creates a new registration profile together with a new user in the user table. how do I tweak this such that I am able to add the user entry into the custom user table. I have tried to create a modelAdmin and alter the save_model method to launch the create_inactive_user from django_registration, however I do not how to save the user object generated from django_registration into my Parent table when I have using model inheritance and I do not have a Foreign key attribute in my parent model.

    Read the article

  • python/django problem with sessions and language

    - by freakish
    Hello everyone! I have the following problem: on the main page I can change language. New language is saved in request.session['django_language']. I also have SESSION_COOKIE_DOMAIN set to my site, so session should be inherited by subdomains. And it is, because after changing language I check request.session['django_language'] in subdomains and it's fine. Then I use django.middleware.locale.LocaleMiddleware to translate my pages. And it works perfectly... only on main site! If I change language and refresh main site - it is ok. However, if I change language and go to a subpage (for example /LogIn), then the page is NOT translated at all. It stays on default language. This is really strange, because if I use {% load i18n %} {% get_current_language as lang %} in this subpage, then lang is good language. There is no mistake. What kind of problem can it be? Some suggestions?

    Read the article

  • Django Threaded Commenting System

    - by Yasin Ozel
    (and sorry for my english) I am learning Python and Django. Now, my challange is developing threaded generic comment system. There is two models, Post and Comment. -Post can be commented. -Comment can be commented. (endless/threaded) -Should not be a n+1 query problem in system. (No matter how many comments, should not increase the number of queries) My current models are like this: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() child = generic.GenericRelation( 'Comment', content_type_field='parent_content_type', object_id_field='parent_object_id' ) class Comment(models.Model): content = models.TextField() child = generic.GenericRelation( 'self', content_type_field='parent_content_type', object_id_field='parent_object_id' ) parent_content_type = models.ForeignKey(ContentType) parent_object_id = models.PositiveIntegerField() parent = generic.GenericForeignKey( "parent_content_type", "parent_object_id") Are my models right? And how can i get all comment (with hierarchy) of post, without n+1 query problem? Note: I know mttp and other modules but I want to learn this system. Edit: I run "Post.objects.all().prefetch_related("child").get(pk=1)" command and this gave me post and its child comment. But when I wanna get child command of child command a new query is running. I can change command to ...prefetch_related("child__child__child...")... then still a new query running for every depth of child-parent relationship. Is there anyone who has idea about resolve this problem?

    Read the article

  • Django QuerySet filter method returns multiple entries for one record

    - by Yaroslav
    Trying to retrieve blogs (see model description below) that contain entries satisfying some criteria: Blog.objects.filter(entries__title__contains='entry') The results is: [<Blog: blog1>, <Blog: blog1>] The same blog object is retrieved twice because of JOIN performed to filter objects on related model. What is the right syntax for filtering only unique objects? Data model: class Blog(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Entry(models.Model): title = models.CharField(max_length=100) blog = models.ForeignKey(Blog, related_name='entries') def __unicode__(self): return self.title Sample data: b1 = Blog.objects.create(name='blog1') e1 = Entry.objects.create(title='entry 1', blog=b1) e1 = Entry.objects.create(title='entry 2', blog=b1)

    Read the article

  • django models objects filter

    - by ha22109
    Hello All, I have a model 'Test' ,in which i have 2 foreignkey models.py class Test(models.Model): id =models.Autofield(primary_key=True) name=models.ForeignKey(model2) login=models.ForeignKey(model1) status=models.CharField(max_length=200) class model1(models.Model): id=models.CharField(primary_key=True) . . is_active=models.IntergerField() class model2(model.Model): id=models.ForeignKey(model1) . . status=model.CharField(max_length=200) When i add object in model 'Test' , if i select certain login then only the objects related to that objects(model2) should be shown in field 'name'.How can i achieve this.THis will be runtime as if i change the login field value the objects in name should also change.

    Read the article

  • Advanced Django query with subselects and custom JOINS

    - by Bryan Ward
    I have been investigating this number theoretic function (found in the Height model) and I need to query for things based on the prime factorization of the primary key, or id. I have created a model for Factors of the id which maintains all of the prime factors. class Height(models.Model): b = models.IntegerField(null=True, blank=True) c = models.IntegerField(null=True, blank=True) d = models.FloatField(null=True, blank=True) class Factors(models.Model): height = models.ForeignKey(Height, null=True, blank=True) factor = models.IntegerField(null=True, blank=True) degree = models.IntegerField(null=True, blank=True) prime_id = models.IntegerField(null=True, blank=True) For example, if id=24, then the associated entries in the factors table would be height_id=24,factor=2,degree=3,prime_id=0 height_id=24,factor=3,degree=1,prime_id=1 the prime_id keep track of the relative order of the primes. Now let p < q < r < s all be prime numbers and a,b,c,d be positive integers. Then I want to be able to query for all Heights of the form id=(p**a)*(q**b)*(r**c)*(s**d). Now this is simple in the case that all of p,q,r,s,a,b,c,d are known in that I can just run Height.objects.get(id=(p**a)*(q**b)*(r**c)*(s**d)) But I need to be able to query for something like (2**a)*(3**2)*(r**c)*(s**d) where r,s,a,d are unknown and all Heights of such form will be returned. Furthermore, not all of the rows in Height will have exactly four prime factors, so I need to make sure that I am not matching rows of the form id=(p**a)*(q**b)*(r**c)*(s**d)*(t**e)... From what I can tell, the following MySQL query accomplishes this, but I would like to do it through the Django ORM. I also don't know if this MySQL query is the proper way to go about doing things. SELECT h.*,count(f.height_id) AS factorsCount FROM height AS h LEFT JOIN factors AS f ON ( f.height_id = h.id AND f.height_id IN (SELECT height_id FROM factors where prime_id=1 AND factor=2 AND degree=1) AND f.height_id IN (SELECT height_id FROM factors where prime_id=2 AND factor=3 AND degree=2) AND f.height_id IN (SELECT height_id FROM factors where prime_id=3 AND factor=5 AND degree=1) AND f.height_id IN (SELECT height_id FROM factors where prime_id=4 AND factor=7 ANd degree=1) ) GROUP BY h.id HAVING factorsCount=4 ORDER BY h.id; Any ideas or suggestions for things to try?

    Read the article

  • Django version in GAE

    - by Alex
    I'm tring to use Django 1.1 in GAE, But when I uncomment use_library('django', '1.1') in this script import os os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from google.appengine.dist import use_library #use_library('django', '1.1') # Google App Engine imports. from google.appengine.ext.webapp import util # Force Django to reload its settings. from django.conf import settings settings._target = None import django.core.handlers.wsgi import django.core.signals import django.db import django.dispatch.dispatcher # Unregister the rollback event handler. django.dispatch.dispatcher.disconnect( django.db._rollback_on_exception, django.core.signals.got_request_exception) def main(): # Create a Django application for WSGI. application = django.core.handlers.wsgi.WSGIHandler() # Run the WSGI CGI handler with that application. util.run_wsgi_app(application) if __name__ == "__main__": main() I receives AttributeError: 'module' object has no attribute 'disconnect' What is going on?

    Read the article

  • Django Admin: not seeing any app (permission problem?)

    - by Facundo
    I have a site with Django running some custom apps. I was not using the Django ORM, just the view and templates but now I need to store some info so I created some models in one app and enabled the Admin. The problem is when I log in the Admin it just says "You don't have permission to edit anything", not even the Auth app shows in the page. I'm using the same user created with syncdb as a superuser. In the same server I have another site that is using the Admin just fine. Using Django 1.1.0 with Apache/2.2.10 mod_python/3.3.1 Python/2.5.2, with psql (PostgreSQL) 8.1.11 all in Gentoo Linux 2.6.23 Any ideas where I can find a solution? Thanks a lot. UPDATE: It works from the development server. I bet this has something to do with some filesystem permission but I just can't find it. UPDATE2: vhost configuration file: <Location /> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE gpx.settings PythonDebug On PythonPath "['/var/django'] + sys.path" </Location> UPDATE 3: more info /var/django/gpx/init.py exists and is empty I run python manage.py from /var/django/gpx directory The site is GPX, one of the apps is contable and lives in /var/django/gpx/contable the user apache is webdev group and all these directories and files belong to that group and have rw permission UPDATE 4: confirmed that the settings file is the same for apache and runserver (renamed it and both broke) UPDATE 5: /var/django/gpx/contable/init.py exists This is the relevan part of urls.py: urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), ) urlpatterns += patterns('gpx', (r'^$', 'menues.views.index'), (r'^adm/$', 'menues.views.admIndex'),

    Read the article

  • Django 1.4 dependency when packaging a Precise application

    - by Caustic
    I am trying to package a program I wrote that depends on Django 1.4.1 in Ubuntu 12.04. As Django 1.4.1 isn't available in Precise I am wondering if it is best to: Package up Django 1.4.1 and drop it in my ppa OR write a script that wgets Django at build time and installs. OR Something better that I haven't thought of. I am still inexperienced with packaging and would appreciate some advice Thanks

    Read the article

  • unittest import error with virtualenv + google-app-engine-django

    - by Ray Yun
    I'm working with google-app-engine-django + zipped django. Just running "python manage.py test" succeeded without error. But with virtualenv, test was failed with "import unittest error". same error with Django 1.1. - OSX 10.5.6 - google-app-engine-django (r101 via svn) : r100 was failed with launcher 1.3.0 - GoogleAppLauncher 1.3.0 - Django 1.1 & 1.1.1 (zipped) : both failed - virtualenv 1.4.5 - virtualenvwrapper 1.24 Error Message: (django_appengine)Reiot:warclouds Reiot$ python manage.py test WARNING:root:Could not read datastore data from /var/folders/UZ/UZ1vQeLFH2ShHk4kIiLcFk+++TI/-Tmp-/django_google-app-engine-django.datastore INFO:root:zipimporter('/Volumes/data/Documents/warclouds/django.zip', 'django/core/serializers/') .WARNING:root:Can't open zipfile /Users/Reiot/.virtualenvs/django_appengine/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg: IOError: [Errno 13] file not accessible: '/Users/Reiot/.virtualenvs/django_appengine/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg' WARNING:root:Can't open zipfile /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg: IOError: [Errno 13] file not accessible: '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg' ERROR:root:Exception encountered handling request Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3177, in _HandleRequest self._Dispatch(dispatcher, self.rfile, outfile, env_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3120, in _Dispatch base_env_dict=env_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 515, in Dispatch base_env_dict=base_env_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2379, in Dispatch self._module_dict) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2289, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2185, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "/Volumes/data/Documents/warclouds/main.py", line 28, in <module> from appengine_django import InstallAppengineHelperForDjango File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1264, in Decorate return func(self, *args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1914, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1264, in Decorate return func(self, *args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1816, in FindAndLoadModule description) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1264, in Decorate return func(self, *args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 1767, in LoadModuleRestricted description) File "/Volumes/data/Documents/warclouds/appengine_django/__init__.py", line 44, in <module> import unittest ImportError: No module named unittest INFO:root:"GET / HTTP/1.1" 500 - INFO:root:zipimporter('/Users/Reiot/.virtualenvs/django_appengine/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '') INFO:root:zipimporter('/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg', '') F........................................................... ====================================================================== FAIL: a request to the default page works in the dev_appserver ---------------------------------------------------------------------- Traceback (most recent call last): File "/Volumes/data/Documents/warclouds/appengine_django/tests/integration_test.py", line 176, in testBasic self.assertEquals(rv.status_code, 200) AssertionError: 500 != 200 I also tried with console import but it was ok. > which python /Users/Reiot/.virtualenvs/django_appengine/bin/python > python >>> import unittest Here is my environments: $ mkvirtualenv --no-site-packages no-django $ mkvirtualenv --no-site-packages django-1.1 $ mkvirtualenv --no-site-packages django-1.1.1 (django-1.1)$ easy_install Django-1.1.tar (django-1.1.1)$ easy_install Django-1.1.1.tar $ mkdir google-app-engine-django-svn $ cp -r google-app-engine-django-svn google-app-engine-django-svn-django-1.1 // copy appropriate django.zip $ cp -r google-app-engine-django-svn google-app-engine-django-svn-django-1.1.1 // copy appropriate django.zip

    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

  • Ubuntu 12.04.1 Update Manager and synaptic Package Manager not working

    - by Ashoke
    Recently installed Ubuntu 12.04.1, 64bit on Intel Quad core system. There is a Red Circle with a WHITE 'minus' sign on the upper right hand corner. In the end of a long message displayed below the RED CIRCLE in 'grey' says that INSTALLED PACKAGES HAVE UNMET DEPENDENCIES. None of the following is working. 1. Ubuntu Software Center not opening. UPDATE MANAGER Could not initialize the package information An unresolvable problem occurred while initializing the package information. Please report this bug against the 'update-manager' package and include the following error message: 'E:Encountered a section with no Package: header, E:Problem with MergeList /var/lib/apt/lists/in.archive.ubuntu.com_ubuntu_dists_precise-updates_multiverse_binary-i386_Packages, E:The package lists or status file could not be parsed or opened.' SYNAPTIC PACKAGE MANAGER AN ERROR OCCURED The following details are provided E: Encountered a section with no Package: header E: Problem with MergeList /var/lib/apt/lists/in.archive.ubuntu.com_ubuntu_dists_precise-updates_multiverse_binary-i386_Packages E: The package lists or status file could not be parsed or opened. E: _cache-open() failed, please report. Otherwise, the computer is working fine with broadband WiFi internet. InstallPLEASE HELP.

    Read the article

  • Overwrite clean method in Django Custom Forms

    - by John
    Hi I have wrote a custom widget class AutoCompleteWidget(widgets.TextInput): """ widget to show an autocomplete box which returns a list on nodes available to be tagged """ def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, name=name) if not self.attrs.has_key('id'): final_attrs['id'] = 'id_%s' % name if not value: value = '[]' jquery = u""" <script type="text/javascript"> $("#%s").tokenInput('%s', { hintText: "Enter the word", noResultsText: "No results", prePopulate: %s, searchingText: "Searching..." }); $("body").focus(); </script> """ % (final_attrs['id'], reverse('ajax_autocomplete'), value) output = super(AutoTagWidget, self).render(name, "", attrs) return output + mark_safe(jquery) class MyForm(forms.Form): AutoComplete = forms.CharField(widget=AutoCompleteWidget) this widget uses a jquery function which autocompletes a word based on entries from the database. You can preset its initial values by setting prePopulate to a json string in the form ['name': 'some name', 'id': 'some id'] I do this by setting the inital value of the form field to this json string jquery_string = ['name': 'some name', 'id': 'some id'] form = MyForm(initial={'AutoComplete':jquery_string}) When submitting the form the the value of AutoComplete is returned as a comma seperated list of the selected ids e.g. 12,45,43,66 which if what I want. However if there is an error in the form, for example a required field has not been entered the value of the AutoComplete field is now 12,45,43,66 and not the json string which it requires. What is the best way to solve this. I was thinking about overwriting the clean method in the form class but I'm not sure how to find out if any other element has returned an error. e.g. if forms.errors form.cleaned_date['autocomplete'] = json string return form.cleaned_data Thanks

    Read the article

  • django admin: Add a "remove file" field for Image- or FileFields

    - by w-
    I was hunting around the net for a way to easily allow users to blank out imagefield/filefields they have set in the admin. I found this http://www.djangosnippets.org/snippets/894/ What was really interesting to me here was the code posted in the comment by rfugger remove_the_file = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_the_file'): object.the_file = '' return object When i try to use this in my own form I basically added this to my admin.py which already had a BlahAdmin class BlahModelForm(forms.ModelForm): class Meta: model = Blah remove_img01 = forms.BooleanField(required=False) def save(self, *args, **kwargs): object = super(self.__class__, self).save(*args, **kwargs) if self.cleaned_data.get('remove_img01'): object.img01 = '' return object when i run it I get this error maximum recursion depth exceeded while calling a Python object at this line object = super(self.__class__, self).save(*args, **kwargs) When i think about it for a bit, it seems obvious that it is just infinitely calling itself causing the error. My problem is i can't figure out what is the correct way i should be doing this. Any suggestions? thanks

    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 templates array assignment

    - by Hulk
    The following is in views: rows=query.evaluation_set.all() row_arr = [] for row in rows: row_arr.append(row.row_details) dict.update({'row_arr' : row_arr ,'col_arr' : col_arr}) return render_to_response('valuemart/show.html',context_instance=RequestContext(request,{'dict': dict})) How to extract the row_Arr array in the templates in javascript and list out all its values.row_Arr contains data of a column <script> var row_arr = '{{dict.row_arr}}'; //extract values here </script> Thanks..

    Read the article

  • django views getid

    - by Hulk
    class host(models.Model): emp = models.ForeignKey(getname) def __unicode__(self): return self.topic In views there is the code as, real =[] for emp in my_emp: real.append(host.objects.filter(emp=emp.id)) This above results only the values of emp,My question is that how to get the ids along with emp values. Thanks..

    Read the article

  • django-admin: creating,saving and relating a m2m model

    - by pastylegs
    I have two models: class Production(models.Model): gallery = models.ManyToManyField(Gallery) class Gallery(models.Model): name = models.CharField() I have the m2m relationship in my productions admin, but I want that functionality that when I create a new Production, a default gallery is created and the relationship is registered between the two. So far I can create the default gallery by overwriting the productions save: def save(self, force_insert=False, force_update=False): if not ( Gallery.objects.filter(name__exact="foo").exists() ): g = Gallery(name="foo") g.save() self.gallery.add(g) This creates and saves the model instance (if it doesn't already exist), but I don't know how to register the relationship between the two?

    Read the article

  • Django Formset management-form validation error

    - by gramware
    I have a form and a formset on my template. The problem is that the formset is throwing validation error claiming that the management form is "missing or has been tampered with". Here is my view @login_required def home(request): user = UserProfile.objects.get(pk=request.session['_auth_user_id']) blogz = list(blog.objects.filter(deleted='0')) delblog = modelformset_factory(blog, exclude=('poster','date' ,'title','content')) if request.user.is_staff== True: staff = 1 else: staff = 0 staffis = 1 if request.method == 'POST': delblogformset = delblog(request.POST) if delblogformset.is_valid(): delblogformset.save() return HttpResponseRedirect('/home') else: delblogformset = delblog(queryset=blog.objects.filter( deleted='0')) blogform = BlogForm(request.POST) if blogform.is_valid(): blogform.save() return HttpResponseRedirect('/home') else: blogform = BlogForm(initial = {'poster':user.id}) blogs= zip(blogz,delblogformset.forms) paginator = Paginator(blogs, 10) # Show 25 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: blogs = paginator.page(page) except (EmptyPage, InvalidPage): blogs = paginator.page(paginator.num_pages) return render_to_response('home.html', {'user':user, 'blogform':blogform, 'staff': staff, 'staffis': staffis, 'blog':blogs, 'delblog':delblogformset}, context_instance = RequestContext( request )) my template {%block content%} <h2>Home</h2> {% ifequal staff staffis %} {% if form.errors %} <ul> {% for field in form %} <H3 class="title"> <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p> </H3> {% endfor %} </ul> {% endif %} <h3>Post a Blog to the Front Page</h3> <form method="post" id="form2" action="" class="infotabs accfrm"> {{ blogform.as_p }} <input type="submit" value="Submit" /> </form> <br> <br> {% endifequal %} <div class="pagination"> <span class="step-links"> {% if blog.has_previous %} <a href="?page={{ blog.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ blog.number }} of {{ blog.paginator.num_pages }}. </span> {% if blog.has_next %} <a href="?page={{ blog.next_page_number }}">next</a> {% endif %} </span> <form method="post" action="" class="usertabs accfrm"> {{delblog.management_form}} {% for b, form in blog.object_list %} <div class="blog"> <h3>{{b.title}}</h3> <p>{{b.content}}</p> <p>posted by <strong>{{b.poster}}</strong> on {{b.date}}</p> {% ifequal staff staffis %}<p>{{form.as_p}}<input type="submit" value="Delete" /></p>{% endifequal %} </div> {% endfor %} </form> {%endblock%}

    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

  • Filter Queryset in Django inlineformset_factory

    - by Dave
    I am trying to use inlineformset_factory to generate a formset. My models are defined as: class Measurement(models.Model): subject = models.ForeignKey(Animal) experiment = models.ForeignKey(Experiment) assay = models.ForeignKey(Assay) values = models.CommaSeparatedIntegerField(blank=True, null=True) class Experiment(models.Model): date = models.DateField() notes = models.TextField(max_length = 500, blank=True) subjects= models.ManyToManyField(Subject) in my view i have: def add_measurement(request, experiment_id): experiment = get_object_or_404(Experiment, pk=experiment_id) MeasurementFormSet = inlineformset_factory(Experiment, Measurement, extra=10, exclude=('experiment')) if request.method == 'POST': formset = MeasurementFormSet(request.POST,instance=experiment) if formset.is_valid(): formset.save() return HttpResponseRedirect( experiment.get_absolute_url() ) else: formset = MeasurementFormSet(instance=experiment) return render_to_response("data_entry_form.html", {"formset": formset, "experiment": experiment }, context_instance=RequestContext(request)) but i want to restrict the Measurement.subject field to only subjects defined in the Experiment.subjects queryset. I have tried a couple of different ways of doing this but I am a little unsure what the best way to accomplish this is. I tried to over-ride the BaseInlineFormset class with a new queryset, but couldnt figure out how to correctly pass the experiment parameter.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >