Search Results

Search found 4979 results on 200 pages for 'django fan'.

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

  • 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

  • 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

  • Why is my CPU fan so loud?

    - by tiiquu
    I bought an old PC to use as a second PC. Everything is fine, except for one thing. The CPU fan is terribly loud! I did a lot with PCs but I never did much with CPU fans. If I want to replace it, what do I have to look for? The fan is 8cm long on each side and 11cm diameter. It is just clipped to the cooler. The PC is a P4 3 GHz. I don't want to spend much money, as I only paid 50 euro for the whole PC. I would prefer to buy a fan for 1-3 dollar or something at eBay but I am not quite sure which one I should buy (which fits). Can you advise?

    Read the article

  • How to control fan speed using SpeedFan?

    - by John Young
    The CPU fan in my laptop is running too fast. I wish to control the speed manually to my preference, at times. Here is a CPU-Z screenshot of my laptop configuration: http://i.stack.imgur.com/1oST1.png And here is how SpeedFan window looks at my end: http://i.imgur.com/BIi0RdJ.jpg I have no idea how to use SpeedFan to control my laptop's CPU fan speed. How to configure it so that I can increase and decrease speed of the fan at my will? Edit: Sorry, the first image wasn't as intended, so I've corrected it now. Also, if someone can edit the post and embed the images in the post, that would be great. I need at least 10 reputation to successfully accomplish that.

    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

  • Coolbits not working

    - by usk
    I want to use coolbits to increase fan speed of my Fermi GPU. 280.13 driver installed. Ubuntu 11.10 I edited /etc/X11/xorg.conf as follows, by pressing Alt+F2 and gksu gedit /etc/X11/xorg.conf I get Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "GeForce GTX 470" Option "NoLogo" "True" Option "Coolbits" "4" EndSection Started getting these messages, Gtk-WARNING **: Unable to locate theme engine in module_path: "pixmap" So I did this, sudo aptitude install gtk2-engines-pixbuf terminal, a@z:~$ nvidia-settings -a [gpu:0]/GPUFanControlState=1 a@z:~$ nvidia-settings -q fans 1 Fan on z:0 [0] z:0[fan:0] (Fan 0) a@z:~$ nvidia-settings -a [fan:0]/GPUCurrentFanSpeed=80 ERROR: Error assigning value 80 to attribute 'GPUCurrentFanSpeed' (z:0[fan:0]) as specified in assignment '[fan:0]/GPUCurrentFanSpeed=80' (Unknown Error). So, it's not working; I can't enter the fan speed percentage. Also from NVidia X Server, there are no fan controls. http://en.gentoo-wiki.com/wiki/Nvidia#Manual_Fan_Control_for_nVIDIA_Settings

    Read the article

  • Fan speed monitor Software for Macbook Pro Unibody on Windows

    - by dtmunir
    I've tried multiple temperature monitor and fan speed software on my Macbook Pro Unibody under Windows 7 64-bit RC. None of them can report the fan speed. Currently I'm using SpeedFan which reports the CPU temperature of each of the two cores, but is not able to detect or interface with the Fans. Has anyone had any luck with this?

    Read the article

  • loud fan on laptop

    - by Doug
    My laptop (hp dv6500t) fan is really loud! What can I do to decrease the sound? I checked the bios with no options and I can't used speedfna because it doesn't work. Can I chagbe it's faN Edit: I already cleaned out the fans and even added artic silver 5. It's loud where people can hear it accross the classroom.

    Read the article

  • Brand new Mac Pro tower fan suddenly runs full-tilt

    - by Caffeine Coma
    My Quad-Core Mac Pro tower is two days old. Initially, I was impressed with how quiet it was compared to my older Macbook Pro. Then on day two, for some reason it started running very loudly. It's not just a "little" loud- my wife walked into the room and asked what the noise was. At first I thought this was just because I was hitting the CPU a bit (importing my iPhone library into iLife '09, and running Eclipse). But now that that's done, Activity Monitor shows a virtually idle CPU; there's nothing running that ought to be causing this, as far as I can tell. I tried powering it off & letting it cool down for a few minutes to no avail; about 10 seconds after powering up, the box gets loud again. I took a look at it with the side cover off, and it seems to be the fan near the top middle, between the power supply and the disk drive. It can't be a dust issue, as the machine is only 2 days old (and I peeked inside anyway just to be sure- clean). I did do a software update over the past 24 hours or so, but I can't say that it occurred immediately after that. I also did a migration of my old apps and data from my MBPro, for what it's worth. Why is it suddenly so loud? How can I monitor the fan speed and various system temperatures? Here's a link to my temps and fan speeds. UPDATE 1: Took it to the Apple Store. They took it in the back (where it's presumably quieter) and ran a fan diagnostic; no problems were found. The guy also told me that it was "a little loud", but normal. I don't buy it. It was virtually silent the first 24 hours I was using it. They would not replace/service it in the store (grrr... that's why I went there, as directed by Apple Care) but said I could get a replacement from the online store, as it was just purchased. I think I will try that. UPDATE 2: Apple is letting me send it back for a replacement. Glad to see so many responses to this question mentioning that the MacPros are usually silent; it's not all just in my head. :-)

    Read the article

  • fan adapter required for 2 controlers

    - by spy
    good day i would like to ask if i can connect the same fan to 2 fan controllers at the same time, if so how do i go about it please, i bought http://www.ebay.co.uk/itm/121255084003?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1497.l2649 wich has a loger cable and sits on my table and http://www.ebay.co.uk/itm/111365380971?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1497.l2649 sits in the tower and facing away from me.

    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

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