Search Results

Search found 3554 results on 143 pages for 'django modelforms'.

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

  • 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

  • django error ,about django-sphinx

    - by zjm1126
    from django.db import models from djangosphinx.models import SphinxSearch class MyModel(models.Model): search = SphinxSearch() # optional: defaults to db_table # If your index name does not match MyModel._meta.db_table # Note: You can only generate automatic configurations from the ./manage.py script # if your index name matches. search = SphinxSearch('index_name') # Or maybe we want to be more.. specific searchdelta = SphinxSearch( index='index_name delta_name', weights={ 'name': 100, 'description': 10, 'tags': 80, }, mode='SPH_MATCH_ALL', rankmode='SPH_RANK_NONE', ) queryset = MyModel.search.query('query') results1 = queryset.order_by('@weight', '@id', 'my_attribute') results2 = queryset.filter(my_attribute=5) results3 = queryset.filter(my_other_attribute=[5, 3,4]) results4 = queryset.exclude(my_attribute=5)[0:10] results5 = queryset.count() # as of 2.0 you can now access an attribute to get the weight and similar arguments for result in results1: print result, result._sphinx # you can also access a similar set of meta data on the queryset itself (once it's been sliced or executed in any way) print results1._sphinx and Traceback (most recent call last): File "D:\zjm_code\sphinx_test\models.py", line 1, in <module> from django.db import models File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module> if not settings.DATABASE_ENGINE: File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__ self._setup() File "D:\Python25\Lib\site-packages\django\conf\__init__.py", line 38, in _setup raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

    Read the article

  • Django TemplateSyntaxError only on live server (templates exist)

    - by Tom
    I'm getting a strange error that only occurs on the live server. My Django templates directory is set up like so base.html two-column-base.html portfolio index.html extranet base.html index.html The portfolio pages work correctly locally on multiple machines. They inherit from either the root base.html or two-column-base.html. However, now that I've posted them to the live box (local machines are Windows, live is Linux), I get a TemplateSyntaxError: "Caught TemplateDoesNotExist while rendering: base.html" when I try to load any portfolio pages. It seems to be a case where the extends tag won't work in that root directory (???). Even if I do a direct_to_template on two-column-base.html (which extends base.html), I get that error. The extranet pages all work perfectly, but those templates all live inside the /extranet folder and inherit from /extranet/base.html. Possible issues I've checked: file permissions on the server are fine the template directory is correct on the live box (I'm using os.path.dirname(os.path.realpath(__file__)) to make things work across machines) files exist and the /templates directories exactly match my local copy removing the {% extends %} block from the top of any broken template causes the templates to render without a problem manually starting a shell session and calling get_template on any of the files works, but trying to render it blows up with the same exception on any of the extended templates. Doing the same with base.html, it renders perfectly (base.html also renders via direct_to_template) Django 1.2, Python 2.6 on Webfaction. Apologies in advance because this is my 3rd or 4th "I'm doing something stupid" question in a row. The only x-factor I can think of is this is my first time using Mercurial instead ofsvn. Not sure how I could have messed things up via that. EDIT: One possible source of problems: local machine is Python 2.5, live is 2.6. Here's a traceback of me trying to render 'two-column-base.html', which extends 'base.html'. Both files are in the same directory, so if it can find the first, it can find the second. c is just an empty Context object. >>> render_to_string('two-column-base.html', c) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader.py", line 186, in render_to_string return t.render(context_instance) File "/home/lightfin/webapps/django/lib/python2.6/django/template/__init__.py", line 173, in render return self._render(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/__init__.py", line 167, in _render return self.nodelist.render(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/__init__.py", line 796, in render bits.append(self.render_node(node, context)) File "/home/lightfin/webapps/django/lib/python2.6/django/template/debug.py", line 72, in render_node result = node.render(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader_tags.py", line 103, in render compiled_parent = self.get_parent(context) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader_tags.py", line 100, in get_parent return get_template(parent) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader.py", line 157, in get_template template, origin = find_template(template_name) File "/home/lightfin/webapps/django/lib/python2.6/django/template/loader.py", line 138, in find_template raise TemplateDoesNotExist(name) TemplateSyntaxError: Caught TemplateDoesNotExist while rendering: base.html I'm wondering if this is somehow related to the template caching that was just added to Django. EDIT 2 (per lazerscience): template-related settings: import os PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates'), ) sample view: def project_list(request, jobs, extra_context={}): context = { 'jobs': jobs, } print context context.update(extra_context) return render_to_response('portfolio/index.html', context, context_instance=RequestContext(request)) The templates in reverse-order are: http://thosecleverkids.com/junk/index.html http://thosecleverkids.com/junk/portfolio-base.html http://thosecleverkids.com/junk/two-column-base.html http://thosecleverkids.com/junk/base.html though in the real project the first two live in a directory called "portfolio".

    Read the article

  • Changing data in a django modelform

    - by Matt Hampel
    I get data in from POST and validate it via this standard snippet: entry_formset = EntryFormSet(request.POST, request.FILES, prefix='entries') if entry_formset.is_valid(): .... The EntryFormSet modelform overrides a foreign key field widget to present a text field. That way, the user can enter an existing key (suggested via an Ajax live search), or enter a new key, which will be seamlessly added. I use this try-except block to test if the object exists already, and if it doesn't, I add it. entity_name = request.POST['entries-0-entity'] try: entity = Entity.objects.get(name=entity_name) except Entity.DoesNotExist: entity = Entity(name=entity_name) entity.slug = slugify(entity.name) entity.save() However, I now need to get that entity back into the entry_formset. It thinks that entries-0-entity is a string (that's how it came in); how can I directly access that value of the entry_formset and get it to take the object reference instead?

    Read the article

  • Django ModelForm for Many-to-Many fields

    - by theycallmemorty
    Consider the following models and form: class Pizza(models.Model): name = models.CharField(max_length=50) class Topping(models.Model): name = models.CharField(max_length=50) ison = models.ManyToManyField(Pizza, blank=True) class ToppingForm(forms.ModelForm): class Meta: model = Topping When you view the ToppingForm it lets you choose what pizzas the toppings go on and everything is just dandy. My questions is: How do I define a ModelForm for Pizza that lets me take advantage of the Many-to-Many relationship between Pizza and Topping and lets me choose what Toppings go on the Pizza?

    Read the article

  • How to create a UserProfile form in Django with first_name, last_name modifications ?

    - by Natim
    If think my question is pretty obvious and almost every developer working with UserProfile should be able to answer it. However, I could not find any help on the django documentation or in the Django Book. When you want to do a UserProfile form in with Django Forms, you'd like to modify the profile fields as well as some User field. But there is no forms.UserProfileForm (yet?) ! How do you do that ?

    Read the article

  • 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 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

  • Using a custom form in a modelformset factory?

    - by jamida
    I'd like to be able to use a customized form in a modelformset_factory. For example: models.py class Author(models.Model): name = models.CharField() address = models.CharField() class AuthorForm(ModelForm): class Meta: model = Author views.py def test_render(request): myModelFormset = modelformset_factory(Author) items = Author.objects.all() formsetInstance = myModelFormset(queryset = items) return render_to_response('template',locals()) The above code works just fine, but note I'm NOT using AuthorForm. The question is how can I get the modelformset_factory to use the AuthorForm (which I plan to customize later) instead of making a default Author form?

    Read the article

  • Form for Profile models ?

    - by xRobot
    Is there a way to create a form from profile models ? For example... If I have this model as profile: class blogger(models.Model): user = models.ForeignKey(User, unique=True) born = models.DateTimeField('born') gender = models.CharField(max_length=1, choices=gender ) about = models.TextField(_('about'), null=True, blank=True) . I want this form: Name: Surname: Born: Gender: About: Is this possible ? If yes how ?

    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

  • 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

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