Search Results

Search found 3555 results on 143 pages for 'django queryset'.

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

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

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

    Read the article

  • Is there an OR filter? - Django

    - by RadiantHex
    Hi folks, is there any way of doing the following Unicorn.objects.or_filter(magical=True).or_filter(unicorn_length=15).or_filter(skin_color='White').or_filter(skin_color='Blue') where or_filter stands for an isolated match I remember using something similar but cannot find the function anymore! Help would be great! Thanks :)

    Read the article

  • Matching 3 out 5 fields - Django

    - by RadiantHex
    Hi folks, I'm finding this a bit tricky! Maybe someone can help me on this one I have the following model: class Unicorn(models.Model): horn_length = models.IntegerField() skin_color = models.CharField() average_speed = models.IntegerField() magical = models.BooleanField() affinity = models.CharField() I would like to search for all similar unicorns having at least 3 fields in common. Is it too tricky? Or is it doable?

    Read the article

  • Django many to many annotations and filters

    - by dl8
    So I have two models, Person and Film where they're in a many to many relationship. My goal is to grab a film, and output the persons that have also appeared in at least 10 films. For example I can get the count individually by: >>> Person.objects.get(short__istartswith = "Matt Damon").film_set.count() 71 However, if I try to filter all the actors of a particular film out: >>> Film.objects.get(name__istartswith="Saving Private Ryan").actors.all().annotate(film_count=Count('film')).filter(film_count__gte=10) [] it returns an empty set since if I manually look at everyone's film_count it's 1, even though an actor such as Matt Damon (as seen above) has been in 71 films in my db. As you can see with this query, the annotation doesn't work: >>> Film.objects.get(name__istartswith="Saving Private Ryan").actors.all().annotate(film_count=Count('film'))[0].film_count 1 >>> Film.objects.get(name__istartswith="Saving Private Ryan").actors.all().annotate(film_count=Count('film'))[0].film_set.count() 7 and I can't seem to figure out a way to filter it by the film_set.count()

    Read the article

  • django auth : strange error with authenticate()

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

    Read the article

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

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

    Read the article

  • Django deployment - can't import app.urls

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

    Read the article

  • Django "comment_was_flagged" signal

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

    Read the article

  • django-multilingual and switching between languages on template side

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

    Read the article

  • Edit/show Primary Key in Django Admin

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

    Read the article

  • Django Admin Actions missing

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

    Read the article

  • Django authentication in django nonrel on GAE

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

    Read the article

  • How can I copy a queryset to a new model in django admin?

    - by user3806832
    I'm trying to write an action that allows the user to select the queryset and copy it to a new table. So: John, Mark, James, Tyler and Joe are in a table 1( called round 1) The user selects the action that say to "move to next round" and those same instances that were chosen are now also in the table for "round 2". I started trying with an action but don't really know where to go from here: def Round_2(modeladmin, request, queryset): For X in queryset: X.pk = None perform.short_description = "Move to Round 2" How can I copy them to the next table with all of their information (pk doesn't have to be the same)? Thanks

    Read the article

  • django form ModelChoiceField loads all state names while needed states which are mapped with current selected country

    - by Sonu
    I am using modelChoiceField to display country and state into address form class StateSelectionwidget(forms.Select): """ custom widget to state selection""" class Media: js = ('media/javascript/public/jquery-1.5.2.min.js', 'media/javascript/public/countrystateselection.js', ) class AddressForm(forms.Form): name = forms.CharField(max_length=30) country = forms.ModelChoiceField(queryset=[]) state = forms.ModelChoiceField(CountryState.objects, widget=StateSelectionwidget) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) self.fields['country'].queryset = Country.objects.all() Country model is used to store country names. CountryState model is used to store all states which is foreign key to Country model At the time of form loading i am getting all state names in dropdown while i want field to be blank by default. If name field is empty at the time of form save i am getting error that name can not be empty but also getting all states into dropdown list while i want only the states which are mapped with current selected country.

    Read the article

  • PyDev and Django: PyDev breaking Django shell?

    - by Rosarch
    I've set up a new project, and populated it with simple models. (Essentially I'm following the tut.) When I run python manage.py shell on the command line, it works fine: >python manage.py shell Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from mysite.myapp.models import School >>> School.objects.all() [] Works great. Then, I try to do the same thing in Eclipse (using a Django project that is composed of the same files.) Right click on mysite project Django Shell with Django environment This is the output from the PyDev Console: >>> import sys; print('%s %s' % (sys.executable or sys.platform, sys.version)) C:\Python26\python.exe 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] >>> >>> from django.core import management;import mysite.settings as settings;management.setup_environ(settings) 'path\\to\\mysite' >>> from mysite.myapp.models import School >>> School.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python26\lib\site-packages\django\db\models\query.py", line 68, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 83, in __len__ self._result_cache.extend(list(self._iter)) File "C:\Python26\lib\site-packages\django\db\models\query.py", line 238, in iterator for row in self.query.results_iter(): File "C:\Python26\lib\site-packages\django\db\models\sql\query.py", line 287, in results_iter for rows in self.execute_sql(MULTI): File "C:\Python26\lib\site-packages\django\db\models\sql\query.py", line 2368, in execute_sql cursor = self.connection.cursor() File "C:\Python26\lib\site-packages\django\db\backends\__init__.py", line 81, in cursor cursor = self._cursor() File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py", line 170, in _cursor self.connection = Database.connect(**kwargs) OperationalError: unable to open database file What am I doing wrong here?

    Read the article

  • Django: UserProfile with Unique Foreign Key in Django Admin

    - by lazerscience
    Hi, I have extended Django's User Model using a custom user profile called UserExtension. It is related to User through a unique ForeignKey Relationship, which enables me to edit it in the admin in an inline form! I'm using a signal to create a new profile for every new user: def create_user_profile(sender, instance, created, **kwargs): if created: try: profile, created = UserExtension.objects.get_or_create(user=instance) except: pass post_save.connect(create_user_profile, sender=User) (as described here for example: http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django) The problem is, that, if I create a new user through the admin, I get an IntegritiyError on saving "column user_id is not unique". It doesnt seem that the signal is called twice, but i guess the admin is trying to save the profile AFTERWARDS? But I need the creation through signal if I create a new user in other parts of the system!

    Read the article

  • How to open python scripts directly by typing in their name in terminal (Mac OS X)

    - by Haffi112
    I'm working on installing django and running it on my system. I have a problem though, in this tutorial creating a project is explained by running the command django-admin.py startproject mysite My issue is that this doesn't work. I changed to the directory where django-admin.py is located and ran the command chmod +x django-admin.py with no results. I tried adding the directory with the file to my path without results. I ended up fixing my problem with this command python /location/of/django-admin.py startproject mysite which yielded the outcome I expected. My problem is: What do I need to change/configure such that command django-admin.py startproject mysite would be sufficient? Here are some experiments: 21:09~/Desktop/HI/NSN/Polls > django-admin.py startproject mysite -bash: django-admin.py: command not found 21:09~/Desktop/HI/NSN/Polls > ./django-admin.py startproject mysite -bash: ./django-admin.py: No such file or directory 21:09~/Desktop/HI/NSN/Polls > python django-admin.py startproject mysite python: can't open file 'django-admin.py': [Errno 2] No such file or directory 21:09~/Desktop/HI/NSN/Polls > /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py startproject prufa1 -bash: /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py: /opt/local/bin: bad interpreter: Permission denied 21:09~/Desktop/HI/NSN/Polls > sudo /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py startproject prufa1Password: sudo: unable to execute /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py: Permission denied 21:09~/Desktop/HI/NSN/Polls > sudo /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py startproject prufa1sudo: unable to execute /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py: Permission denied 21:09~/Desktop/HI/NSN/Polls > python /opt/local/lib/python2.4/site-packages/django/bin/django-admin.py startproject prufa1 21:09~/Desktop/HI/NSN/Polls > ls mysite prufa1 Final edit: The problem is solved, see Ian C's answer for the right solution. Thank you everyone for helping my out, this was very fast!

    Read the article

  • Django: Validation error in Admin

    - by tomwolber
    NEWBIE ALERT! background: For the first time, I am writing a model that needs to be validated. I cannot have two Items that have overlapping "date ranges". I have everything working, except when I raise forms.ValidationError, I get the yellow screen of death (debug=true) or a 500 page (debug=false). My question: How can I have an error message show up in the Admin (like when you leave a required filed blank)? Sorry for my inexperience, please let me know if I can clarify the question better. Models.py from django.db import models from django import forms from django.forms import ModelForm from django.db.models import Q class Item(models.Model): name = models.CharField(max_length=500) slug = models.SlugField(unique=True) startDate = models.DateField("Start Date", unique="true") endDate = models.DateField("End Date") def save(self, *args, **kwargs): try: Item.objects.get(Q(startDate__range=(self.startDate,self.endDate))|Q(endDate__range=(self.startDate,self.endDate))|Q(startDate__lt=self.startDate,endDate__gt=self.endDate)) #check for validation, which may raise an Item.DoesNotExist error, excepted below #if the validation fails, raise this error: raise forms.ValidationError('Someone has already got that date, or somesuch error message') except Item.DoesNotExist: super(Item,self).save(*args,**kwargs) def __unicode__(self): return self.name def get_absolute_url(self): return "/adtest/%s/" % self.slug

    Read the article

  • Django - Override admin site's login form

    - by TrojanCentaur
    I'm currently trying to override the default form used in Django 1.4 when logging in to the admin site (my site uses an additional 'token' field required for users who opt in to Two Factor Authentication, and is mandatory for site staff). Django's default form does not support what I need. Currently, I've got a file in my templates/ directory called templates/admin/login.html, which seems to be correctly overriding the template used with the one I use throughout the rest of my site. The contents of the file are simply as below: # admin/login.html: {% extends "login.html" %} The actual login form is as below: # login.html: {% load url from future %}<!DOCTYPE html> <html> <head> <title>Please log in</title> </head> <body> <div id="loginform"> <form method="post" action="{% url 'id.views.auth' %}"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> {{ form.username.label_tag }}<br/> {{ form.username }}<br/> {{ form.password.label_tag }}<br/> {{ form.password }}<br/> {{ form.token.label_tag }}<br/> {{ form.token }}<br/> <input type="submit" value="Log In" /> </form> </div> </body> </html> My issue is that the form provided works perfectly fine when accessed using my normal login URLs because I supply my own AuthenticationForm as the form to display, but through the Django Admin login route, Django likes to supply it's own form to this template and thus only the username and password fields render. Is there any way I can make this work, or is this something I am just better off 'hard coding' the HTML fields into the form for?

    Read the article

  • Django tests failing on invalid keyword argument

    - by Darwin Tech
    I have a models.py like so: from django.db import models from django.contrib.auth.models import User from datetime import datetime class UserProfile(models.Model): user = models.OneToOneField(User) def __unicode__(self): return self.user.username class Project(models.Model): user = models.ForeignKey(UserProfile) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) product = models.ForeignKey('tool.product') module = models.ForeignKey('tool.module') model = models.ForeignKey('tool.model') zipcode = models.IntegerField(max_length=5) def __unicode__(self): return unicode(self.id) And my tests.py: from django.test import TestCase, Client # --- import app models from django.contrib.auth.models import User from tool.models import Module, Model, Product from user_profile.models import Project, UserProfile # --- unit tests --- # class UserProjectTests(TestCase): fixtures = ['admin_user.json'] def setUp(self): self.product1 = Product.objects.create( name='bar', ) self.module1 = Module.objects.create( name='foo', enable=True ) self.model1 = Model.objects.create( module=self.module1, name='baz', enable=True ) self.user1 = User.objects.get(pk=1) ... def test_can_create_project(self): self.project1 = Model.objects.create( user=self.user1, product=self.product1, module=self.module1, model=self.model1, zipcode=90210 ) self.assertEquals(self.project1.zipcode, 90210) But I get a TypeError: 'product' is an invalid keyword argument for this function error. I'm not sure what is failing but I'm guessing something to do with the FK relationships... Any help would be much appreciated.

    Read the article

  • Django: Overriding the save() method: how do I call the delete() method of a child class

    - by Patti
    The setup = I have this class, Transcript: class Transcript(models.Model): body = models.TextField('Body') doPagination = models.BooleanField('Paginate') numPages = models.PositiveIntegerField('Number of Pages') and this class, TranscriptPages(models.Model): class TranscriptPages(models.Model): transcript = models.ForeignKey(Transcript) order = models.PositiveIntegerField('Order') content = models.TextField('Page Content', null=True, blank=True) The Admin behavior I’m trying to create is to let a user populate Transcript.body with the entire contents of a long document and, if they set Transcript.doPagination = True and save the Transcript admin, I will automatically split the body into n Transcript pages. In the admin, TranscriptPages is a StackedInline of the Transcript Admin. To do this I’m overridding Transcript’s save method: def save(self): if self.doPagination: #do stuff super(Transcript, self).save() else: super(Transcript, self).save() The problem = When Transcript.doPagination is True, I want to manually delete all of the TranscriptPages that reference this Transcript so I can then create them again from scratch. So, I thought this would work: #do stuff TranscriptPages.objects.filter(transcript__id=self.id).delete() super(Transcript, self).save() but when I try I get this error: Exception Type: ValidationError Exception Value: [u'Select a valid choice. That choice is not one of the available choices.'] ... and this is the last thing in the stack trace before the exception is raised: .../django/forms/models.py in save_existing_objects pk_value = form.fields[pk_name].clean(raw_pk_value) Other attempts to fix: t = self.transcriptpages_set.all().delete() (where self = Transcript from the save() method) looping over t (above) and deleting each item individually making a post_save signal on TranscriptPages that calls the delete method Any ideas? How does the Admin do it? UPDATE: Every once in a while as I'm playing around with the code I can get a different error (below), but then it just goes away and I can't replicate it again... until the next random time. Exception Type: MultiValueDictKeyError Exception Value: "Key 'transcriptpages_set-0-id' not found in " Exception Location: .../django/utils/datastructures.py in getitem, line 203 and the last lines from the trace: .../django/forms/models.py in _construct_form form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs) .../django/utils/datastructures.py in getitem pk = self.data[pk_key]

    Read the article

  • Configuration problems with django and mod_wsgi

    - by Jimbo
    Hi, I've got problems on getting django to work on apache 2.2 with mod_wsgi. Django is installed and mod_wsgi too. I can even see a 404 page when accessing the path and I can login to django admin. But if I want to install the tagging module I get the following error: Traceback (most recent call last): File "setup.py", line 49, in <module> version_tuple = __import__('tagging').VERSION File "/home/jim/django-tagging/tagging/__init__.py", line 3, in <module> from tagging.managers import ModelTaggedItemManager, TagDescriptor File "/home/jim/django-tagging/tagging/managers.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/lib/python2.5/site-packages/django/contrib/contenttypes/models.py", line 1, in <module> from django.db import models File "/usr/lib/python2.5/site-packages/django/db/__init__.py", line 10, in <module> if not settings.DATABASE_ENGINE: File "/usr/lib/python2.5/site-packages/django/utils/functional.py", line 269, in __getattr__ self._setup() File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 40, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'mysite.settings' (Is it on sys.path? Does it have syntax errors?): No module named mysite.settings My httpd.conf: Alias /media/ /home/jim/django/mysite/media/ <Directory /home/jim/django/mysite/media> Order deny,allow Allow from all </Directory> Alias /admin/media/ "/usr/lib/python2.5/site-packages/django/contrib/admin/media/" <Directory "/usr/lib/python2.5/site-packages/django/contrib/admin/media/"> Order allow,deny Allow from all </Directory> WSGIScriptAlias /dj /home/jim/django/mysite/apache/django.wsgi <Directory /home/jim/django/mysite/apache> Order deny,allow Allow from all </Directory> My django.wsgi: import sys, os sys.path.append('/home/jim/django') sys.path.append('/home/jim/django/mysite') os.chdir('/home/jim/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() I try to get this to work since a few days and have read several blogs and answers here on so but nothing worked.

    Read the article

  • Why is django giving me an attribute error when I call _set.all() for its children models?

    - by user1876508
    I have two models defined from django.db import models class Blog(models.Model): title = models.CharField(max_length=144) @property def posts(self): self.Post_set.all() class Post(models.Model): title = models.CharField(max_length=144) text = models.TextField() blog = models.ForeignKey('Blog') but the problem is, when I run shell, and enter >>> blog = Blog(title="My blog") >>> post = Post(title="My first post", text="Here is the main text for my blog post", blog=blog) >>> blog.posts I get the error Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/lucas/Programming/Python/Django/djangorestfun/blog/models.py", line 9, in posts self.Post_set.all() AttributeError: 'Blog' object has no attribute 'Post_set' >>> Now I am having the following problem >>> from blog.models import * >>> blog = Blog(title="gewrhter") >>> blog.save() >>> blog.__dict__ {'_state': <django.db.models.base.ModelState object at 0x259be10>, 'id': 1, 'title': 'gewrhter'} >>> blog._state.__dict__ {'adding': False, 'db': 'default'} >>> post = Post(title="sdhxcvb", text="hdbfdgb", blog=blog) >>> post.save() >>> post.__dict__ {'blog_id': 1, 'title': 'sdhxcvb', 'text': 'hdbfdgb', '_blog_cache': <Blog: Blog object>, '_state': <django.db.models.base.ModelState object at 0x259bed0>, 'id': 1} >>> blog.posts >>> print blog.posts None Second update So I followed your guide, but I am still getting nothing. In addition, blog.posts gives me an error. >>> from blog.models import * >>> blog = Blog(title="asdf") >>> blog.save() >>> post = Post(title="asdf", text="sdxcvb", blog=blog) >>> post.save() >>> blog.posts Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Blog' object has no attribute 'posts' >>> print blog.all_posts None

    Read the article

  • Django Error: NameError name 'current_datetime' is not defined

    - by Diego
    I'm working through the book "The Definitive Guide to Django" and am stuck on a piece of code. This is the code in my settings.py: ROOT_URLCONF = 'mysite.urls' I have the following code in my urls.py from django.conf.urls.defaults import * from mysite.views import hello, my_homepage_view urlpatterns = patterns('', ('^hello/$', hello), ) urlpatterns = patterns('', ('^time/$', current_datetime), ) And the following is the code in my views.py file: from django.http import HttpResponse import datetime def hello(request): return HttpResponse("Hello World") def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) Yet, I get the following error when I test the code in the development server. NameError at /time/ name 'current_datetime' is not defined Can someone help me out here? This really is just a copy-paste from the book. I don't see any mistyping.

    Read the article

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