Search Results

Search found 8610 results on 345 pages for 'django filter'.

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

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

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

    Read the article

  • 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

  • Django unable to update model

    - by user292652
    i have the following function to override the default save function in a model match def save(self, *args, **kwargs): if self.Match_Status == "F": Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1) Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1) if self.Winner !="": Team.objects.filter(pk=self.Winner.id).update(Win=F('Win')+1, Points=F('Points')+3) else: return if self.Match_Status == "D": Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1) Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1) super(Match, self).save(*args, **kwargs) I am able to save the match model just fine but Team model does not seem to be updating at all and no error is being thrown. am i missing some thing here ?

    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

  • Django QuerySet filter + order_by + limit

    - by handsofaten
    So I have a Django app that processes test results, and I'm trying to find the median score for a certain assessment. I would think that this would work: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) median_exam = Exam.objects.filter(assessment=assessment.id).order_by('score')[median:1] median_score = median_exam.score But it always returns an empty list. I can get the result I want with this: e = Exam.objects.all() total = e.count() median = int(round(total / 2)) exams = Exam.objects.filter(assessment=assessment.id).order_by('score') median_score = median_exam[median].score I would just prefer not to have to query the entire set of exams. I thought about just writing a raw MySQL query that looks something like: SELECT score FROM assess_exam WHERE assessment_id = 5 ORDER BY score LIMIT 690,1 But if possible, I'd like to stay within Django's ORM. Mostly, it's just bothering me that I can't seem to use order_by with a filter and a limit. Any ideas?

    Read the article

  • Django: remove a filter condition from a queryset

    - by Don
    I have a third-part funtion which gives me a filtered queryset (e.g. records with 'valid'=True) but I want to remove a particular condition (e.g. to have all records, both valid and invalid). Is there a way to remove a filter condition to an already-filtered queryset? E.g. only_valid = MyModel.objects.filter(valid=True) all_records = only_valid.**remove_filter**('valid') (I know that it would be better to define 'all_records' before 'only_valid', but this is just an example...)

    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

  • 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

  • Django Admin drop down combobox and assigned values

    - by Daniel Garcia
    I have several question for the Django Admin feature. Im kind of new in Django so im not sure how to do it. Basically what Im looking to do is when Im adding information on the model. Some of the fields i want them to be drop-downs and maybe combo-boxes with AutoCompleteMode. Also looking for some fields to have the same information, for example if i have a datatime field I want that information to feed the fields day, month and year from hoti.hotiapp.models import Occurrence from django.contrib import admin class MyModelAdmin(admin.ModelAdmin): exclude = ['reference',] admin.site.register(Occurrence, MyModelAdmin) Anything helps Thanks in advance

    Read the article

  • Alternate datasource for django model?

    - by slypete
    I'm trying to seamlessly integrate some legacy data into a django application. I would like to know if it's possible to use an alternate datasource for a django model. For example, can I contact a server to populate a list of a model? The server would not be SQL based at all. Instead it uses some proprietary tcp based protocol. Copying the data is not an option, as the legacy application will continue to be used for some time. Would a custom manager allow me to do this? This model should behave just like any other django model. It should even pluggable to the admin interface. What do you think? Thanks, Pete

    Read the article

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