Search Results

Search found 9098 results on 364 pages for 'django admin'.

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

  • Django Admin Running Same Query Thousands of Times for Model

    - by Tom
    Running into an odd . . . loop when trying to view a model in the Django admin. I have three related models (code trimmed for brevity, hopefully I didn't trim something I shouldn't have): class Association(models.Model): somecompany_entity_id = models.CharField(max_length=10, db_index=True) name = models.CharField(max_length=200) def __unicode__(self): return self.name class ResidentialUnit(models.Model): building = models.CharField(max_length=10) app_number = models.CharField(max_length=10) unit_number = models.CharField(max_length=10) unit_description = models.CharField(max_length=100, blank=True) association = models.ForeignKey(Association) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __unicode__(self): return '%s: %s, Unit %s' % (self.association, self.building, self.unit_number) class Resident(models.Model): unit = models.ForeignKey(ResidentialUnit) type = models.CharField(max_length=20, blank=True, default='') lookup_key = models.CharField(max_length=200) jenark_id = models.CharField(max_length=20, blank=True) user = models.ForeignKey(User) is_association_admin = models.BooleanField(default=False, db_index=True) show_in_contact_list = models.BooleanField(default=False, db_index=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) _phones = {} home_phone = None work_phone = None cell_phone = None app_number = None account_cache_key = None def __unicode__(self): return '%s' % self.user.get_full_name() It's the last model that's causing the problem. Trying to look at a Resident in the admin takes 10-20 seconds. If I take 'self.association' out of the __unicode__ method for ResidentialUnit, a resident page renders pretty quickly. Looking at it in the debug toolbar, without the association name in ResidentialUnit (which is a foreign key on Resident), the page runs 14 queries. With the association name put back in, it runs a far more impressive 4,872 queries. The strangest part is the extra queries all seem to be looking up the association name. They all come from the same line, the __unicode__ method for ResidentialUnit. Each one is the exact same thing, e.g., SELECT `residents_association`.`id`, `residents_association`.`jenark_entity_id`, `residents_association`.`name` FROM `residents_association` WHERE `residents_association`.`id` = 1096 ORDER BY `residents_association`.`name` ASC I assume I've managed to create a circular reference, but if it were truly circular, it would just die, not run 4000x and then return. Having trouble finding a good Google or StackOverflow result for this.

    Read the article

  • Django: How to get current user in admin forms

    - by lazerscience
    In Django's ModelAdmin I need to display forms customized according to the permissions an user has. Is there a way of getting the current user object into the form class, so that i can customize the form in its __init__ method? I think saving the current request in a thread local would be a possibility but this would be my last resort think I'm thinking it is a bad design approach....

    Read the article

  • Django: name of many to many items in the admin interface

    - by Adam
    I have a many to many field, which I'm displaying in the django admin panel. When I add multiple items, they all come up as "ASGGroup object" in the display selector. Instead, I want them to come up as whatever the ASGGroup.name field is set to. How do I do this? My models looks like: class Thing(Model): read_groups = ManyToManyField('ASGGroup', related_name="thing_read", blank=True) class ASGGroup(Model): name = CharField(max_length=63, null=True) But what I'm seeing the m2m widget display is:

    Read the article

  • Accessing updated M2M fields in overriden save() in django's admin

    - by Jonathan
    I'd like to use the user updated values of a ManyToManyField in a model's overriden save() method when I save an instance in admin. It turns out that by design, django does not update the M2M field before calling save(), but only after the save() is complete as part of the form save... How can I access the new values of this field in the override save() ?

    Read the article

  • Django Admin Form for Many to many relationship

    - by Anand
    I have a many to many relationship between 2 tables Users an Domains. I have defined this relationship in the Domains class. So in the admin interface I see the Users when I am viewing Domains. But I do not see Domains when I am viewing Users. How can I achieve this.

    Read the article

  • django admin - adding fields on the fly

    - by Thomas
    Basically I am writing a simple shopping cart. Each item can have multiple prices. (i.e. shirts where each size is priced differently). I would like to have a single price field in my admin panel, where when the first price is entered, an additional price field pops up. However I am kind of at a loss as to how to do this. What would be the best way to do this?

    Read the article

  • How to display total record count against models in django admin

    - by Rog
    Is there a neat way to make the record/object count for a model appear on the main model list in the admin module? I have found techniques for showing counts of related objects within sets in the list_display page (and I can see the total in the pagination section at the bottom of the same), but haven't come across a neat way to show the record count at the model list level.

    Read the article

  • Django: How to set default language in admin on login

    - by lazerscience
    I'm saving an user's default language in his user profile and on login I want to set the admin's default language to it. One possibility I was thinking of is using a middleware, but I think if I do it on process_request I will not see an user object there since this is processed AFTER the middleware, so I could only set it after the next request! Any solutions are highly appreciated!

    Read the article

  • django internationalization doesn't work

    - by xRobot
    I have: created translation strings in the template and in the application view. run this command: django-admin.py makemessages -l it and the file it/LC_MESSAGES/django.po has been created run this command: django-admin.py compilemessages and I receive: processing file django.po in /home/jobber/Desktop/library/books/locale/it/LC_MESSAGES set the language code in settings.py: LANGUAGE_CODE = 'it-IT' but.... translation doesn't work !! I always see english text. Why ?

    Read the article

  • So now that Django 1.2 is officially out...

    - by Fedor
    Since I have Django 1.1x on my Debian setup - how can I use virtualenv or similar and not have it mess up my system's default django version which in turn would break all my sites? Detailed instructions or a great tutorial link would very much be appreciated - please don't offer vague advice since I'm still a noob. Currently I store all my django projects in ~/django-sites and I am using Apache2 + mod_wsgi to deploy.

    Read the article

  • Django-Registration & Django-Profile, using your own custom form

    - by Issy
    Hey All, I am making use of django-registration and django-profile to handle registration and profiles. I would like to create a profile for the user at the time of registration. I have created a custom registration form, and added that to the urls.py using the tutorial on: http://dewful.com/?p=70 The basic idea in the tutorial is to override the default registration form to create the profile at the same time. forms.py - In my profiles app from django import forms from registration.forms import RegistrationForm from django.utils.translation import ugettext_lazy as _ from profiles.models import UserProfile from registration.models import RegistrationProfile attrs_dict = { 'class': 'required' } class UserRegistrationForm(RegistrationForm): city = forms.CharField(widget=forms.TextInput(attrs=attrs_dict)) def save(self, profile_callback=None): new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email']) new_profile = UserProfile(user=new_user, city=self.cleaned_data['city']) new_profile.save() return new_user In urls.py from profiles.forms import UserRegistrationForm and url(r'^register/$', register, {'backend': 'registration.backends.default.DefaultBackend', 'form_class' : UserRegistrationForm}, name='registration_register'), The form is displayed, and i can enter in City, however it does not save or create the entry in the DB.

    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

  • 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

  • UnicodeEncodeError when uploading files in Django admin

    - by Samuel Linde
    Note: I asked this question on StackOverflow, but I realize this might be a more proper place to ask this kind of question. I'm trying to upload a file called 'Testaråäö.txt' via the Django admin app. I'm running Django 1.3.1 with Gunicorn 0.13.4 and Nginx 0.7.6.7 on a Debian 6 server. Database is PostgreSQL 8.4.9. Other Unicode data is saved to the database with no problem, so I guess the problem must be with the filesystem somehow. I've set http { charset utf-8; } in my nginx.conf. LC_ALL and LANG is set to 'sv_SE.UTF-8'. Running 'locale' verifies this. I even tried setting LC_ALL and LANG in my nginx init script just to make sure locale is set properly. Here's the traceback: Traceback (most recent call last): File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/handlers/base.py", line 111, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/options.py", line 307, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 93, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/views/decorators/cache.py", line 79, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/sites.py", line 197, in inner return view(request, *args, **kwargs) File "/srv/django/letebo/app/cms/admin.py", line 81, in change_view return super(PageAdmin, self).change_view(request, obj_id) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 28, in _wrapper return bound_func(*args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 93, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/utils/decorators.py", line 24, in bound_func return func(self, *args2, **kwargs2) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/transaction.py", line 217, in inner res = func(*args, **kwargs) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/options.py", line 985, in change_view self.save_formset(request, form, formset, change=True) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/contrib/admin/options.py", line 677, in save_formset formset.save() File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/forms/models.py", line 482, in save return self.save_existing_objects(commit) + self.save_new_objects(commit) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/forms/models.py", line 613, in save_new_objects self.new_objects.append(self.save_new(form, commit=commit)) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/forms/models.py", line 717, in save_new obj.save() File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/base.py", line 460, in save self.save_base(using=using, force_insert=force_insert, force_update=force_update) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/base.py", line 504, in save_base self.save_base(cls=parent, origin=org, using=using) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/base.py", line 543, in save_base for f in meta.local_fields if not isinstance(f, AutoField)] File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/fields/files.py", line 255, in pre_save file.save(file.name, file, save=False) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/db/models/fields/files.py", line 92, in save self.name = self.storage.save(name, content) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 48, in save name = self.get_available_name(name) File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 74, in get_available_name while self.exists(name): File "/srv/.virtualenvs/letebo/lib/python2.6/site-packages/django/core/files/storage.py", line 218, in exists return os.path.exists(self.path(name)) File "/srv/.virtualenvs/letebo/lib/python2.6/genericpath.py", line 18, in exists st = os.stat(path) UnicodeEncodeError: 'ascii' codec can't encode characters in position 52-54: ordinal not in range(128) I tried running Gunicorn with debugging turned on, and the file uploads without any problem at all. I suppose this must mean that the issue is with Nginx. Still beats me where to look, though. Here are the raw response headers from Gunicorn and Nginx, if it makes any sense: Gunicorn: HTTP/1.1 302 FOUND Server: gunicorn/0.13.4 Date: Thu, 09 Feb 2012 14:50:27 GMT Connection: close Transfer-Encoding: chunked Expires: Thu, 09 Feb 2012 14:50:27 GMT Vary: Cookie Last-Modified: Thu, 09 Feb 2012 14:50:27 GMT Location: http://my-server.se:8000/admin/cms/page/15/ Cache-Control: max-age=0 Content-Type: text/html; charset=utf-8 Set-Cookie: messages="yada yada yada"; Path=/ Nginx: HTTP/1.1 500 INTERNAL SERVER ERROR Server: nginx/0.7.67 Date: Thu, 09 Feb 2012 14:50:57 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Connection: close Vary: Cookie 500 UPDATE: Both locale.getpreferredencoding() and sys.getfilesystemencoding() outputs 'UTF-8'. locale.getdefaultlocale() outputs ('sv_SE', 'UTF8'). This seem correct to me, so I'm still not sure why I keep getting these errors.

    Read the article

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

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

    Read the article

  • Modify on-the-fly verbose_name in a model field on django admin

    - by PerroVerd
    Hi I have this sample model working with the admin class Author(models.Model): name = models.CharField(_('Text in here'), max_length=100) with verbose_name set as ugettext_lazy 'Text in here', but sometimes, depending on the site_id i want to present a diferent verbose name, so I modified the init in this way def __init__(self, *args, **kwargs): super(Author, self).__init__(*args, **kwargs) #some logic in here self._meta.get_field('name').verbose_name = _('Other text') It works, displaying the 'Other text' instead the 'Text in here'... except for the very first time the author/add view is used. ¿Is it the right way to do it? ¿How can i fix the first time problem? Thanks in advance

    Read the article

  • How do I reference Django Model from another model

    - by user313943
    Im looking to create a view in the admin panel for a test program which logs Books, publishers and authors (as on djangoproject.com) I have the following two models defined. class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title What I want to do, is change the Book model to reference the first_name of any authors and show this using admin.AdminModels. #Here is the admin model I've created. class BookAdmin(admin.ModelAdmin): list_display = ('title', 'publisher', 'publication_date') # Author would in here list_filter = ('publication_date',) date_hierarchy = 'publication_date' ordering = ('-publication_date',) fields = ('title', 'authors', 'publisher', 'publication_date') filter_horizontal = ('authors',) raw_id_fields = ('publisher',) As I understand it, you cannot have two ForeignKeys in the same model. Can anyone give me an example of how to do this? I've tried loads of different things and its been driving me mad all day. Im pretty new to Python/Django. Just to be clear - I'd simply like the Author(s) First/Last name to appear alongside the book title and publisher name. Thanks

    Read the article

  • Calling a method from within a django model save() override

    - by Jonathan
    I'm overriding a django model save() method. Within the override I'm calling another method of the same class and instance which calculates one of the instance's fields based on other fields of the same instance. class MyClass(models.Model): field1 = models.FloatField() field2 = models.FloatField() field3 = models.FloatField() def calculateField1(self) self.field1 = self.field2 + self.field3 def save(self, *args, **kwargs): self.calculateField1() super(MyClass, self).save(*args, **kwargs) The override method is called when I change the model in admin. Alas I've discovered that within calculateField1() field2 and field3 have the values of the instance from before I edited them in admin. If I enter the instance again in admin and save again, only then field1 receives the correct value as field2 and field3 are already updated. Is this the correct behavior on django's side? If yes, then how can I use the new values within calculateField1? I cannot implement the calculation within the save() as calculateField1() actually quite long and I need it to be called from elsewhere.

    Read the article

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

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

    Read the article

  • 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

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