How to set the CURRENT_TIMESTAMP in a datetime field
Hi all guys. I tried to look for around a way to set a datetime field with the CURRENT_TIMESTAMP value. I found nothing useful. Did I miss anything? Imagine some processes running on parallel servers: what when one process has to set a datetime field to "now" where "now" MUST BE set using the db-server time? Forget about triggers because that field can assume values different from "now". Should it be possible doing something like : foo = Foo.objects.get(...) #foo.thedatetime = datetime.datetime.now() foo.thedatetime = "current_timestamp" #where thedatetime is a DateTime field foo.save() Thank you --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: How to deal with this Internationalization ?
sorry , the correct code is below . I change the login.py into forms.py > -- > settings.py > > # Django settings for Test project. > > DEBUG = True > TEMPLATE_DEBUG = DEBUG > > ADMINS = ( > # ('Your Name', 'your_em...@domain.com'), > ) > > MANAGERS = ADMINS > > DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', > 'postgresql', 'mysql', 'sqlite3' or 'oracle'. > DATABASE_NAME = 'test' # Or path to database file if using > sqlite3. > DATABASE_USER = 'root' # Not used with sqlite3. > DATABASE_PASSWORD = '123456' # Not used with sqlite3. > DATABASE_HOST = '127.0.0.1' # Set to empty string for > localhost. Not used with sqlite3. > DATABASE_PORT = '' # Set to empty string for default. Not > used with sqlite3. > TIME_ZONE = 'America/Chicago' > LANGUAGE_CODE = 'en' > SITE_ID = 1 > USE_I18N = True > MEDIA_ROOT = '' > MEDIA_URL = '' > ADMIN_MEDIA_PREFIX = '/media/' > > SECRET_KEY = '%5(1wm^_wws6f3pq#_ypz...@#htypxft+7i*lcp4jx0nf5192' > > TEMPLATE_LOADERS = ( > ) > > MIDDLEWARE_CLASSES = ( > 'django.contrib.sessions.middleware.SessionMiddleware', > 'django.middleware.locale.LocaleMiddleware', > 'django.middleware.common.CommonMiddleware', > 'django.contrib.auth.middleware.AuthenticationMiddleware', > 'django.middleware.doc.XViewMiddleware', > ) > > ROOT_URLCONF = 'Test.urls' > > TEMPLATE_DIRS = ( > 'D:/work/Test/templates' > ) > > TEMPLATE_CONTEXT_PROCESSORS = ( > 'django.core.context_processors.i18n', > 'django.core.context_processors.request', > ) > > INSTALLED_APPS = ( > 'django.contrib.auth', > 'django.contrib.contenttypes', > 'django.contrib.sessions', > 'django.contrib.sites', > 'Test.login', > ) > - > > urls.py > > from django.conf.urls.defaults import * > from Test.login.views import login_method > > urlpatterns = patterns('', > (r'^i18n/', include('django.conf.urls.i18n')), > (r'^test/$',login_method), > ) > -- > views.py > > from django.shortcuts import render_to_response > from Test.login.forms import LoginForm > from django.utils.translation import check_for_language,get_language > def login_method(request): > r_list = '' > username = '' > password = '' > lang = request.LANGUAGE_CODE > print 'before POST,the language is %(lang)s' %{'lang':lang} > if request.method == 'POST': > lang_code=request.POST.get("language") > request.session['django_language'] = lang_code > session = request.session.get('django_language') > form = LoginForm(request.POST) > if form.is_valid(): > username = form.cleaned_data['username'] > password = form.cleaned_data['password'] > form = LoginForm() > else: > form = LoginForm() > r_list = {'username':username,'password':password} > return render_to_response('test.html', > {'form':form,'r_list':r_list}) > - >forms.py from django import forms from django.forms import widgets from django.utils.translation import gettext_lazy as _ class LoginForm(forms.Form): array = ( ('zh-CN', _('Simplified chinese')), ('zh-TW', _('Traditional chinese')), ('en-us', _('English')), ) username = forms.CharField(max_length=50,required=True,label = _ ("username")) password = forms.CharField (max_length=50,required=True,widget=widgets.PasswordInput(),label = _ ("password")) language = forms.CharField (max_length=50,required=True,widget=forms.Select(choices=array),label = _("language")) > > test.html > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";> > {% load i18n %} > {% get_current_language as LANGUAGE_CODE %} > http://www.w3.org/1999/xhtml";> > > > test > > > > > > {% trans "login" %} > > > > > > {{form}} > > > > > > > > > > {% ifnotequal r_list.get('username') ''%} > {% trans 'username' %} : {{r_list.username|default:"nothing"}} {% > trans 'password' %} : {{r_list.password|default:"nothing"}} > {% endifnotequal %} > > -- > > Is there anything wrong ? --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: How to deal with this Internationalization ?
Now,I have designed a Demo . It contains username ,password, and language . But ,when I submit , it can't work . what's wrong ? -- settings.py # Django settings for Test project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_em...@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'test' # Or path to database file if using sqlite3. DATABASE_USER = 'root' # Not used with sqlite3. DATABASE_PASSWORD = '123456' # Not used with sqlite3. DATABASE_HOST = '127.0.0.1' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en' SITE_ID = 1 USE_I18N = True MEDIA_ROOT = '' MEDIA_URL = '' ADMIN_MEDIA_PREFIX = '/media/' SECRET_KEY = '%5(1wm^_wws6f3pq#_ypz...@#htypxft+7i*lcp4jx0nf5192' TEMPLATE_LOADERS = ( ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', ) ROOT_URLCONF = 'Test.urls' TEMPLATE_DIRS = ( 'D:/work/Test/templates' ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.i18n', 'django.core.context_processors.request', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'Test.login', ) - urls.py from django.conf.urls.defaults import * from Test.login.views import login_method urlpatterns = patterns('', (r'^i18n/', include('django.conf.urls.i18n')), (r'^test/$',login_method), ) -- views.py from django.shortcuts import render_to_response from Test.login.forms import LoginForm from django.utils.translation import check_for_language,get_language def login_method(request): r_list = '' username = '' password = '' lang = request.LANGUAGE_CODE print 'before POST,the language is %(lang)s' %{'lang':lang} if request.method == 'POST': lang_code=request.POST.get("language") request.session['django_language'] = lang_code session = request.session.get('django_language') form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] form = LoginForm() else: form = LoginForm() r_list = {'username':username,'password':password} return render_to_response('test.html', {'form':form,'r_list':r_list}) - login.py from login.models import Mlogin class login(object): def new(self,username,password): login_result = Mlogin.objects.create( username = username , password = password , ) return login_result def getresult(self): result = Mnewconrecord.objects.all() return result test.html {% load i18n %} {% get_current_language as LANGUAGE_CODE %} http://www.w3.org/1999/xhtml";> test {% trans "login" %} {{form}} {% ifnotequal r_list.get('username') ''%} {% trans 'username' %} : {{r_list.username|default:"nothing"}} {% trans 'password' %} : {{r_list.password|default:"nothing"}} {% endifnotequal %} -- Is there anything wrong ? --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: File upload: how to validate file type
Hallöchen! Torsten Bronger writes: > I'd like to ensure that people only upload PDF files, so the file > must start with "%PDF". If the file starts with something else, > the form must not validate. > > How do I do that? I though about a clean_... method which reads > the start of the file and then re-opens it. Is this a good idea? At least this works. A look at the source code revealed that every UploadedFile object must have an open() method, so re-opening it should be safe, no matter which storage system or uploaded file type is in use. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bron...@jabber.rwth-aachen.de --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: What hash algorithm does django auth use?
On Mon, 2009-03-30 at 12:50 +1100, Joshua Partogi wrote: > Hi all, > > I tried saving the password data with this function > > import hashlib > hashlib.md5( new_member.password ).hexdigest() > > but when I log in again with that password it doesnt work. A number of problems here. Firstly, Django uses SHA1 as the default hashing algorithm. Secondly, you haven't accounted for including any salt in the password hash (which make the task of dictionary attacks much harder). The correct way to set a user's password is to call the set_password() method on the user object. You pass in the plaintext password and set_password() does the necessary hashing. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Best Convension for dealing with variables needed in every view.
I've never really understood why the context processor list wasn't part of the default settings.py. But I've always just copied and pasted the complete list into settings. On Sun, Mar 29, 2009 at 7:40 PM, IanR wrote: > > So I see that I can easily create a context_processor to do this stuff > for me. > > It says that these are the default context_processors. I can not find > them in the settings.py, where is this located? (I grepped my whole > project so it must be somewhere else) > > TEMPLATE_CONTEXT_PROCESSORS > ("django.core.context_processors.auth", > "django.core.context_processors.debug", > "django.core.context_processors.i18n", > "django.core.context_processors.media") > > So if I created my own I could just add it to this list and it would > do what I need. Once my context_processor is made how would I add it > to this list? Something like > settings.TEMPLATE_CONTEXT_PROCESSORS.append(my_processor) > > > On Mar 29, 7:19 pm, David Zhou wrote: >> On Sun, Mar 29, 2009 at 7:14 PM, IanR wrote: >> > I'm trying to stay a close to the suggested Django conventions as >> > possible. I have a few variables that I need to render any page. >> >> Check out context >> processors:http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-... >> >> > base_media_url, this is the url of where I store all my static files >> > and media, images, javascript, css >> >> This is actually already available if you use the RequestContext, as >> by default, the list of context processors include the media url: >> >> http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-c... >> >> -- dz > > > --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: What hash algorithm does django auth use?
On Sun, Mar 29, 2009 at 9:50 PM, Joshua Partogi wrote: > > I thought we're to use hexdigest ? > > Did I miss something here? You need to salt it: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py#L20 -- dz --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
What hash algorithm does django auth use?
Hi all, I tried saving the password data with this function import hashlib hashlib.md5( new_member.password ).hexdigest() but when I log in again with that password it doesnt work. I thought we're to use hexdigest ? Did I miss something here? Thank you very much in advance -- If you can't believe in God the chances are your God is too small. Read my blog: http://joshuajava.wordpress.com/ Follow me on twitter: http://twitter.com/jpartogi --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
custom form in admin debugging confusion
class ContactAdmin(Admin): form = EditContactForm EditContactForm has a save method that is never called by the Admin but its clean() function does get called 60 def clean(self): 61 import pdb; pdb.set_trace() my confusion is that due to the snakey admin code the form class is created using a different name and is created in the scope of a different module. even though the class is explicitly specified in my Admin, that name is replaced with class_name = model.__name__ + 'Form' self.__class__ (Pdb) self (Pdb) self.save (Pdb) > dir(self) (Pdb) ['Meta', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__unicode__', '__weakref__', '_changed_data', '_errors', '_get_changed_data', '_get_errors', '_get_media', '_html_output', '_meta', 'add_initial_prefix', 'add_prefix', 'as_p', 'as_table', 'as_ul', 'auto_id', 'base_fields', 'changed_data', 'check_for_account', 'clean', 'clean_email', 'data', 'declared_fields', 'empty_permitted', 'error_class', 'errors', 'fields', 'files', 'full_clean', 'has_changed', 'initial', 'instance', 'is_bound', 'is_multipart', 'is_valid', 'label_suffix', 'media', 'non_field_errors', 'prefix', 'save', 'save_from_request', 'validate_unique', 'will_save'] I can see my clean_email method and other methods that I defined. it *is*my class, but its name and module have been changed which makes debugging quite difficult. this leads me on a wild goose-chase trying to figure out why the wrong form was instantiated. is there any reason that normal classes aren't used ? there doesn't seem to be any use of passing in multiple bases and I still don't know why save() isn't called by the admin thankx for any insight --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
MySQL group_concat with aggregates
Hi, I have the model described at http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany on which I have multiple rows in Membership with the same Person and Group (say they're a bit flaky, and leave and rejoin a few times ;) ). I wanted to print out a paginated list of groups someone is in, with all their joining dates in each group result. I decided to try the new aggregate functionality. Here's my view: from aggregates import Concatenate groups = person.group_set .annotate(Concatenate('membership__date_joined')) .order_by('name') page = Paginator(groups, 10).page(1) And my Concatenate class looks like this: from django.db.models import Aggregate from django.db.models.sql.aggregates import Aggregate as AggregateSQL from django.db.models import DecimalField class ConcatenateSQL(AggregateSQL): sql_function = 'GROUP_CONCAT' def __init__(self, col, separator='|', source=None, **extra): self.sql_template = "%%(function)s(%%(field)s ORDER BY %%(field)s SEPARATOR '%s')" % separator c = DecimalField() # XXX super(ConcatenateSQL, self).__init__(col, source=c, **extra) class Concatenate(Aggregate): name = 'Concatenate' def add_to_query(self, query, alias, col, source, is_summary): aggregate = ConcatenateSQL(col, separator=' / ', is_summary=is_summary) query.connection.ops.check_aggregate_support(aggregate) query.aggregates[alias] = aggregate This works lovely, so the only issue I found was that I had to use a fake DecimalField() in order for the result from the database to get past the call to convert_values() in django/db/backends/__init__.py (called from django/db/models/sql/query.py in resolve_aggregate()). This function appears to only want numbers/datetimes to go in, and in this case I'm obviously returning text. Not sure what to suggest as a solution, as there are presumably other things going on of which I'm not aware, but the above works for me :) ATB, Matthew P.S. If anyone's interested, prior to aggregate support, I was doing something like this to get the joining dates per group: groups = person.group_set.all().distinct().order_by('name') page = Paginator(groups, 10).page(1) ids = [ group.id for group in page.object_list ] members = Membership.objects.filter(group__in=ids, person=person) dates_joined = {} for m in members: dates_joined.setdefault(m.group, []).append(m.date_joined) for group in page.object_list: group.dates_joined = dates_joined[group] Which worked fine, but I felt was a bit fiddly. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Max_num in formset
On Sun, 2009-03-29 at 18:01 -0400, Vitaly Babiy wrote: > Maybe I should have said why I ask. > > I have a formset that the formset can not submit more than certain > number of forms. I was not sure if max_num handles this or do I need > to do this with some custom validation? What happened when you tried it out? In normal use it's not going to be possible to submit more than the maximum number of formsets, since they won't be available in the HTML. The only way it would be possible is if the user manually constructed the POST request or you were messing about with things in Javascript and made a mistake. In both cases, I suspect the extra data will be ignored, just like any other extra data in request.POST (designed that way so that you can pass request.POST to a form constructor without having to know what's in the form first). Since the "extra' forms that have been constructed only on the client side won't match the prefix of any expected form, it will be treated as extra data. On the other hand, my first question is the easiest way to find the answer. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: If less than in template language
Sorry, but I really am relatively new to Django, and although I've been poking around for quite a while, I still just can't get that package to work. When I tried to install it inside of the contrib folder, and then add it to the 'installed applications' in the settings.py file, i kept on getting server errors. having 'removed' it from the installed applications, i simply tried to add an 'ifflessthan' to my code in the templates ({% iflessthan counter 0 }) and I got the template error. Sorry to ask you to go into such detail, but what exactly should I do with the template_utils file on my server? thanks --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Best Convension for dealing with variables needed in every view.
So I see that I can easily create a context_processor to do this stuff for me. It says that these are the default context_processors. I can not find them in the settings.py, where is this located? (I grepped my whole project so it must be somewhere else) TEMPLATE_CONTEXT_PROCESSORS ("django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media") So if I created my own I could just add it to this list and it would do what I need. Once my context_processor is made how would I add it to this list? Something like settings.TEMPLATE_CONTEXT_PROCESSORS.append(my_processor) On Mar 29, 7:19 pm, David Zhou wrote: > On Sun, Mar 29, 2009 at 7:14 PM, IanR wrote: > > I'm trying to stay a close to the suggested Django conventions as > > possible. I have a few variables that I need to render any page. > > Check out context > processors:http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-... > > > base_media_url, this is the url of where I store all my static files > > and media, images, javascript, css > > This is actually already available if you use the RequestContext, as > by default, the list of context processors include the media url: > > http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-c... > > -- dz --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: TemplateDoesNotExist error when postmortem says it exists?
On Mon, Mar 30, 2009 at 1:42 AM, Rob Hudson wrote: > > Wow, that was a tricky one to track down... ... > I take it that gets interpreted as a single value tuple. D'oh! That It does, operator precedence notwithstanding (for example, a lambda expression returning a tuple that is being used as an argument to a function may not interpret an unbracketed tuple, but as a second function argument) > What's interesting to me, is that the file path got converted > correctly in the debug output but not in the template loader itself. That's an edge case of string variable expansion: print "Hello %s world" % foo and: print "Hello %s world" % (foo,) give the same result. However, this flexibility isn't automatically extended to any other usage of a single value tuple - the code needs to explicitly allow tuples for input. The template loader doesn't. Yours, Russ Magee %-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Best Convension for dealing with variables needed in every view.
On Sun, Mar 29, 2009 at 7:14 PM, IanR wrote: > I'm trying to stay a close to the suggested Django conventions as > possible. I have a few variables that I need to render any page. Check out context processors: http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors > base_media_url, this is the url of where I store all my static files > and media, images, javascript, css This is actually already available if you use the RequestContext, as by default, the list of context processors include the media url: http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-media -- dz --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Best Convension for dealing with variables needed in every view.
I'm currently converting my website from PHP to Django. I've always loved python and all my backend code is in python. I figured that it might as well make the jump. So far so good, as everything has been very strait forward and a joy. It's definitely making web development fun again. I'm trying to stay a close to the suggested Django conventions as possible. I have a few variables that I need to render any page. base_url, which is the url of my site. So links in my template might look like http://{{base_url}}/section_1/ and so on. base_media_url, this is the url of where I store all my static files and media, images, javascript, css page_size, this is a little weird because sometimes I render pages at 800 width and other times 1024. (I pass this varialbe to a view that renders a dynamic CSS file.) So I need at a minimum these 3 variables to render any page. (There will probably be more as I'm only about 10% done with my conversion). Obviously setting these in every view is a stupid idea. What would the best way to handle this? Could I create some sort of datastructure in my urls.py file and then pass it to every view? --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Can't import flup.server.fcgi
For others running into this problem, pulling from the django trunk and running with the most recent version fixed this problem for me. Thanks! -a. On Mar 19, 8:31 pm, coffeepunk wrote: > > This has been reported as ticket #10556 earlier today. It will be fixed > > in the next few hours, I suspect. So back up a few versions for now or > > apply the patch in that ticket manually. > > Sweet! I've been looking around like crazy, searching on google and > djangoproject but without finding any answer or the ticket. Since I > was on a fresh installed server I was starting to pull my hair, > wondering over why it wouldn't work, but now I know why at least. > > Thanks for the Answer Malcom. > > Best regards --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Max_num in formset
Maybe I should have said why I ask. I have a formset that the formset can not submit more than certain number of forms. I was not sure if max_num handles this or do I need to do this with some custom validation? Vitaly Babiy On Sun, Mar 29, 2009 at 5:57 PM, Vitaly Babiy wrote: > If the count of forms submit goes over the max_num shouldn't it raise and > validation error? > > Thanks, > Vitaly Babiy > --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Problem with Field errors
Jack Orenstein wrote: > On Mar 29, 2009, at 9:35 AM, Matthew Somerville wrote: >> For more information, see >> http://docs.djangoproject.com/en/dev/ref/forms/validation/ > > Thanks, that's really useful to know about. This works for most of > the additional validation I need to do, but doesn't fit so well for > the cross-field validation, (e.g. password and confirm_password > fields match). Or can I do that by overriding Form.is_valid? From the page I provided a link to: "* The Form subclass’s clean() method. This method can perform any validation that requires access to multiple fields from the form at once. This is where you might put in things to check that if field A is supplied, field B must contain a valid e-mail address and the like." ATB, Matthew --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Max_num in formset
If the count of forms submit goes over the max_num shouldn't it raise and validation error? Thanks, Vitaly Babiy --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Howto create related objects in one shot?
On Mar 23, 9:39 am, Malcolm Tredinnick wrote: > On Mon, 2009-03-23 at 00:18 -0700, Yaniv Haber wrote: > > On Mar 23, 1:41 am, Malcolm Tredinnick > > wrote: > > > On Sun, 2009-03-22 at 05:39 -0700, nivhab wrote: > > > > Hi, > > > > > I have the following model: > > > > > class product(models.Model): > > > > productId = models.AutoField(primary_key=True) > > > > name = models.CharField(max_length=200, > > > > unique=True) > > > > description = models.CharField(max_length=200, blank=True) > > > > > class Wishlist(models.Model): > > > > wishId = models.AutoField(primary_key=True) > > > > product = models.ForeignKey(Product) > > > > for_user = models.ForeignKey(User) > > > > notes = models.CharField(max_length=200, blank=True) > > > > > I would like to create one form that lets the user (unknowingly) to > > > > create new product and a wish list related to this product in one > > > > request. The form needs to contain fields for both models. > > > > > I have some very ugly method for doing it but there has to be a > > > > cleaner way. I simply couldn't find any in the docs or examples. > > > > You're probably over-thinking this. > > > > You want a form with some fields in it. When the form is submitted, your > > > view takes the cleaned data from the form, uses that to determine the > > > appropriates values to use to create each model instance and then saves > > > the models. > > > > So create a normal Form subclass (that's documented in the forms > > > documentation), then use the cleaned data (forms documentation) to > > > create model instances (model documentation or the tutorial) and save > > > those. > > > > When you forms don't map directly onto models, then that's fine. That's > > > why the form module is separate from the model module in Django, so that > > > you're not required to only create forms based on models. > > > > Regards, > > > Malcolm > > > Thanks Malcolm. That's what I actually did but I thought there would > > be a better way, as the connection between the form and the models in > > this case is very loose. > > Deliberately so. Your model describes how the data is represented in the > database. It doesn't really have anything to do with presentation. > > > For example, I cannot get the help_text (and > > probably other properties) defined on the model fields. And you need > > to write the save implementation yourself. Just thought there is a > > better way of doing it. > > If your forms are tightly related to your models, you can use a > ModelForm. Since a Django Form subclass (which includes ModelForm > subclasses) represents only part of an HTML form, you can include more > than one Django Form object in a single HTML form. So you *could* use > ModelForms, if that structures your data visually the way you want to. > > However, if you want true general control over the layout, the form no > longer coupled to your models, except as a way of ultimately storing the > data, so using things from the model "automatically" isn't going to be > correct in any case. And, yes, then you have to move the data from the > form to the model yourself (which isn't exactly difficult or lots of > lines of code), since, again, there's not natural correspondence between > the form and the model. > > There are obviously extensions possible to all of this, since ModelForms > are just a Python implementation of a subclass of Form, so you could > write your own version of something customised exactly to your own > needs. Django doesn't provide a lever to for every possibility, since > there are infinitely many such choices. > > Regards, > Malcolm Creating a form yourself isn't lots of code but you lose some (valuable) pieces of code already written for you in ModelForm (for example: handling of update operations). So it is not only about creating some fields but also about implementing some of this functionality by your self. > Since a Django Form subclass (which includes ModelForm > subclasses) represents only part of an HTML form, you can include more > than one Django Form object in a single HTML form. So you *could* use > ModelForms, if that structures your data visually the way you want to. I was actually searching for the right way to do exactly that: use ModelForms and customize their view as you wish while using their added functionality to reduce code complexity. Apparently there are no examples of such a 'complex view' in the current documentation. I pasted the the solution I found into as a [DjangoSnippet](http:// www.djangosnippets.org/snippets/1399/) for anyone who might be interested. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more
Re: TemplateDoesNotExist error when postmortem says it exists?
Wow, that was a tricky one to track down... After putting debug output in django/template/loaders/filesystem.py I saw that filepath was set to: '/Users/rob/git/anglers/anglers/templates/('book/ search_form.html',)' I back tracked that and found that I had a trailing comma in my view code: if not template: template = 'book/search_form.html', I take it that gets interpreted as a single value tuple. D'oh! That got there from a refactor where I copy/pasted that string when it was in an extra_context dictionary and didn't notice the comma. What's interesting to me, is that the file path got converted correctly in the debug output but not in the template loader itself. -Rob --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: TemplateDoesNotExist error when postmortem says it exists?
On Sun, Mar 29, 2009 at 8:28 AM, Karen Tracey wrote: > That generally means the permissions don't allow the code to access the > file. You don't mention if this happens with the dev server (which would > surprise me, since you can load the template from the shell) or only with a > real web server. If it's only with the real web server than I expect the > permissions need to be fixed so that the web server can read the template > file. Yes, it's using the dev server. I did check the permissions just in case and they look fine (-rw-r--r--). What is odd is I'm also using this template from a different view and it loads fine. I'm trying to debug now but I'm about to run out of time and thought I'd throw it out here if anyone else encountered this. Thanks, -Rob --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Serialize references to foreign keys
On Sun, Mar 29, 2009 at 9:49 PM, Kariem wrote: > > I tried using the serialization as documented in > http://docs.djangoproject.com/en/dev/topics/serialization/ and do > something along the lines of > > json = serializers.get_serializer('json')() > json.serialize(o, ensure_ascii=False, fields=fields) > > "o" is a list of models that contain a reference to another model > (foreign key), similar to what is described in [1]: > > ### start > class MyModel(models.Model): > category = models.ForeignKey(Category) > ... > class Category(models.Model) > ... # name, and other attributes > ### end > > I have observed a somewhat unintuitive behavior and would like to ask, > whether this is intended, or I just did not see the right hint in the > documentation: > - If I pass "None" to the 'fields' argument in json.serialize, I > receive the key of the referenced category in the serialized result > along all other fields of MyModel and keys of other referenced models. > - If I pass "['category']" to the 'fields' argument in > json.serialize, the resulting fields are empty (in json: "fields": > { }) > > After stepping through the code, I found out that this behavior is > controlled in django.core.serializers.base.Serializer [2], and that I > can show the referenced category, if I pass 'categ' instead of > 'category' as field name; i.e. passing 'categ' in the fields argument > results in the json "fields": { "category": } > > Could anybody explain why this is the case? Did I miss something in > the documentation, or should I have done something else to have the > keys of the referenced models included in the serialized result? This sounds like you have found a bug. I certainly can't think of any reason that the behaviour your describe would be the intended behaviour. Please open a ticket and provide as much detail as possible so we can reproduce the bug - Django has existing tests for the fields argument to serializers (tests/modeltests/serializers/models.py, line 192) (around line 192), so we will need to work out what is different about your test case, and the more detail we have, the easier this will be. Better still, if you can provide a patch implementing a failing test case for the existing test suite, it will make the task of finding and fixing the problem much easier. Yours, Russ Magee %-) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: TemplateDoesNotExist error when postmortem says it exists?
On Sun, Mar 29, 2009 at 11:18 AM, Rob Hudson wrote: > > This is a stumper... > > I have a very simple view that is a wrapper around the generic view > direct_to_template. The loader finds the template as indicated in the > output "(File exists)", but yet I still get a TemplateDoesNotExist > error. Any ideas? > That generally means the permissions don't allow the code to access the file. You don't mention if this happens with the dev server (which would surprise me, since you can load the template from the shell) or only with a real web server. If it's only with the real web server than I expect the permissions need to be fixed so that the web server can read the template file. Karen --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
TemplateDoesNotExist error when postmortem says it exists?
This is a stumper... I have a very simple view that is a wrapper around the generic view direct_to_template. The loader finds the template as indicated in the output "(File exists)", but yet I still get a TemplateDoesNotExist error. Any ideas? I can go to the Django shell and load it just fine: > ./manage.py shell >>> from django.template.loader import get_template >>> t = get_template('book/search_form.html') >>> t >>> t.name 'book/search_form.html' Copy/Paste from debug output: Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.load_template_source: /Users/rob/git/anglers/anglers/templates/book/search_form.html (File exists) Using loader django.template.loaders.app_directories.load_template_source: /Users/rob/django/django/django/contrib/admin/templates/book/ search_form.html (File does not exist) Traceback: File "/Users/rob/django/django/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/Users/rob/django/django/django/contrib/auth/decorators.py" in __call__ 67. return self.view_func(request, *args, **kwargs) File "/Users/rob/git/anglers/anglers/../anglers/book/views.py" in search_form 102. extra_context=extra_context, File "/Users/rob/django/django/django/views/generic/simple.py" in direct_to_template 17. t = loader.get_template(template) File "/Users/rob/django/django/django/template/loader.py" in get_template 81. source, origin = find_template_source(template_name) File "/Users/rob/django/django/django/template/loader.py" in find_template_source 74. raise TemplateDoesNotExist, name Exception Type: TemplateDoesNotExist at /advanced-search/ Exception Value: book/search_form.html I'm using Django 1.1 beta 1. Thanks, Rob --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Problem with Field errors
On Mar 29, 2009, at 9:35 AM, Matthew Somerville wrote: > > Jack Orenstein wrote: >> On Mar 28, 2009, at 12:26 PM, Daniel Roseman wrote: >> >>> On Mar 28, 4:14 pm, Jack Orenstein wrote: My application needs to validate data from a from beyond the validation of Fields done by django. So in my form handler, I check Form.is_valid, and if that returns true, then I do my own validation. > > If you have a field you need to perform more validation on, what you > should do is give your Form subclass a clean_() method > which > will be called automatically, and should raise a ValidationError if > the > data doesn't validate (which will then put the error in the right > place > for you). Then is_valid() will do Django and your validation together. > For more information, see > http://docs.djangoproject.com/en/dev/ref/forms/validation/ Thanks, that's really useful to know about. This works for most of the additional validation I need to do, but doesn't fit so well for the cross-field validation, (e.g. password and confirm_password fields match). Or can I do that by overriding Form.is_valid? Jack --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Curious Error
You're passing your template variable `classcolors` to the template filter `random`. Looking at the code for random.py: File "/usr/lib/python2.5/random.py", line 248, in choice return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty IndexError: string index out of range As the comment suggests, if `seq` is empty, raise an IndexError. So it appears that `classcolors` is an empty string. On Mar 28, 7:05 pm, Ramdas S wrote: > Can someone advise? I have the same code working in several web sites. But > since moving to 10177, I am getting this error. It sometimes works in Dev > server, in Apache its been a problem > > http://dpaste.com/20529/ > -- > Ramdas S > +91 9342 583 065 --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Testing form posting
You're POSTing the form instance, rather than the postedData. So: response = self.client.post('/myApp/post', form) should be: response = self.client.post('/myApp/post/', postedData) More info here: http://docs.djangoproject.com/en/dev/topics/testing/#making-requests On Mar 28, 9:14 pm, tsmets wrote: > I was wondering how I could test / unittest form posting ? > > class TestSomeRequest(TestCase): > > def testCallDefaultDpasteURL(self): > response = self.client.get('/my_app/') > self.failUnlessEqual(response.status_code, 200) > > def testCallDpasteAboutURL(self): > postedData = { > 'poster' : 'test', > 'code' : SIMPLE_POST, > 'comment' : 'No comment' > } > form = forms.CodePostForm(postedData) > response = self.client.post('/myApp/post', form) > self.failUnlessEqual(response.status_code, 200) > > This does not seems OK ??? > Any hint would be appreciated > > \T, --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Serialize references to foreign keys
I tried using the serialization as documented in http://docs.djangoproject.com/en/dev/topics/serialization/ and do something along the lines of json = serializers.get_serializer('json')() json.serialize(o, ensure_ascii=False, fields=fields) "o" is a list of models that contain a reference to another model (foreign key), similar to what is described in [1]: ### start class MyModel(models.Model): category = models.ForeignKey(Category) ... class Category(models.Model) ... # name, and other attributes ### end I have observed a somewhat unintuitive behavior and would like to ask, whether this is intended, or I just did not see the right hint in the documentation: - If I pass "None" to the 'fields' argument in json.serialize, I receive the key of the referenced category in the serialized result along all other fields of MyModel and keys of other referenced models. - If I pass "['category']" to the 'fields' argument in json.serialize, the resulting fields are empty (in json: "fields": { }) After stepping through the code, I found out that this behavior is controlled in django.core.serializers.base.Serializer [2], and that I can show the referenced category, if I pass 'categ' instead of 'category' as field name; i.e. passing 'categ' in the fields argument results in the json "fields": { "category": } Could anybody explain why this is the case? Did I miss something in the documentation, or should I have done something else to have the keys of the referenced models included in the serialized result? Thank you, Kariem [1] http://groups.google.com/group/django-users/browse_thread/thread/a3dd017a9ec0dadf [2] http://code.djangoproject.com/browser/django/tags/releases/1.0/django/core/serializers/base.py#L46 --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Problem with Field errors
Jack Orenstein wrote: > On Mar 28, 2009, at 12:26 PM, Daniel Roseman wrote: > >> On Mar 28, 4:14 pm, Jack Orenstein wrote: >>> My application needs to validate data from a from beyond the >>> validation of Fields done by django. So in my form handler, I check >>> Form.is_valid, and if that returns true, then I do my own validation. If you have a field you need to perform more validation on, what you should do is give your Form subclass a clean_() method which will be called automatically, and should raise a ValidationError if the data doesn't validate (which will then put the error in the right place for you). Then is_valid() will do Django and your validation together. For more information, see http://docs.djangoproject.com/en/dev/ref/forms/validation/ >> Try self.form._errors['foobar'] instead. > > That works, thank you. > > Why does it work? http://docs.djangoproject.com/en/dev/ref/forms/validation/#form-subclasses-and-modifying-field-errors explains the _errors variable, but I don't think you need it in this case. ATB, Matthew --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: django.contrib.auth.models.User User model can't be saved
Joshua Partogi wrote: > Yes you're right. In my template I only have username, first_name, > last_name, email and password. I also print out the errors too. Nowhere are you printing out non-field specific errors - please read about non_field_errors at http://docs.djangoproject.com/en/dev/ref/forms/validation/ > Are you saying that I should have all the other fields from > django.contrib.auth.models.User too? No, that would be silly. :) You have created a Form that wants every field from User and are not supplying them all. All you have to do is specify the fields you want to use from User using the Meta class as described at http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form Then you can just display the form with form.as_p and it will know it only cares about those fields. ATB, Matthew --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: File upload: how to validate file type
Hallöchen! P M writes: > yes you can, because signature of pdf is in the starting of 1st > chunk of stream... rest of the things are of hardly interest for > libmagic identification... Again, this is not the point. The point is whether I can safely read the first bytes and put them back into the stream (or, in other words, do a seek(0)). If the file was sent into a file in /tmp/, this may work, but my question is whether this approach is compatible with all upload handlers. Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: torsten.bron...@jabber.rwth-aachen.de --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: I love both Django and the Google Web Toolkit. Who else thinks tighter integration would be nice?
sorry about re-beginning this thread but googlegroups decided to "close" responses. i accidentally replied privately to adam as a result, and will endeavour to reproduce what i wrote. as mentioned previously here on django-users, here is the beginnings of achieving exactly what adam is referring to - tighter integration between django and GWT: http://pyjamas.svn.sourceforge.net/viewvc/pyjamas/trunk/pyjs/jsonrpc/django/jsonrpc.py?view=markup as you can see it is a combination of Django Forms with a JSONRPC service. i've added the "save" command (untested) to demonstrate the point. what needs to be added to make this useful is a "describe" command. the "describe" command must return a description of all fields, along with default values, sizes, lengths, types, multi-values, and basically absolutely everything that's needed so that a GWT or Pyjamas app can dynamically create a complete form widget at the client / browser end. the creation can be done by a generic class in much the same way that as_table() works - and so it will need EXACTLY the same full set of information. l. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: IndexError (list index out of range) in admin when updating a regex char primary key
Karen you're always a big help for me on django. Thank you so much! I was imaging the same thing you explained about problems with the objects pointing to the key i want to change. So I was thinking to create a new counter primary key for that model and turn the current primary key into a simple unique attribute. But I posted this thread hoping there could be some error and some solution without the need to change the model. I think this is what I'm gonna do. On 26 Mar, 20:57, Karen Tracey wrote: > On Thu, Mar 26, 2009 at 7:06 AM, TeenSpirit83 > wrote: > > > > > I can't find nothing similar on this group! Can you please help me? > > I get this error trace in the django 1.0.2 admin when updating a char > > primary key in a regex field. > > Thank you in advance! > > I think there's a bit more going on here than you actually describe. Based > on the traceback, you are dealing with an admin page that contains an inline > formset, and you don't mention that at all. I've recreated what you are > describing with a couple of simplified models and admin defs: > > # models.py > from django.db import models > > class ExplicitPK(models.Model): > expk = models.CharField(max_length=24, primary_key=True) > > def __unicode__(self): > return self.expk > > class AssociatedThing(models.Model): > name = models.CharField(max_length=8) > expk = models.ForeignKey(ExplicitPK) > > def __unicode__(self): > return u'%s associated with %s' % (self.name, self.expk) > > # admin.py > from django.contrib import admin > from expk.models import ExplicitPK, AssociatedThing > > class AssocInline(admin.TabularInline): > model = AssociatedThing > > class ExplicitPKAdmin(admin.ModelAdmin): > inlines = [AssocInline] > > admin.site.register(ExplicitPK, ExplicitPKAdmin) > > If I now go into admin and create an ExplicitPK object with the primary key > 'First', and a couple of AssociatedThing objects inline, all is well. If, > however, I then try to change the 'expk' field value from 'First' to > 'Second', and select 'Save', I get a traceback similar to what you report > (slightly different because I'm running with trunk code, not 1.0.2). > > The reason, I think, has to do with the fact that the POST data for the > admin page with inlines contains information for the (in the case I tested > 2) related objects that point to 'First', but after I change the primary key > value to 'Second', a queryset of AssociatedThing objects that point to > 'Second' returns 0 results. The admin tries to create a formset using a > queryset that specifies the new pk value, but the objects in that queryset > don't match up to the POST data in the request. This mismatch results in the > the formset creation code causing list index out of range when trying to > match up the POST data with a non-existent matching objects in the queryset > of AssociatedThings related to 'Second'. > > Now, the admin (or maybe it's basic formset) creation code might should > handle this more gracefully, when the POST data doesn't match the actual > queryset (and there's at least one ticket open on that issue, since it also > surfaces when ordering differs from call to call), but I'm not sure even if > it did that you'd be getting the results you are expecting. What do you > expect to happen when you change the primary key of an object? > > What does happen is that an entirely new object is created. The primary key > value of the existing database row is not changed. That's just how the ORM > works, I believe. When you change the primary key value in the in-memory > model object, the ORM has no way, so far as I know, to know that the primary > key value used to be something else. So when the object is saved, you just > wind up creating a new object (assuming you pick a primary key value that > doesn't already exist in the table), because the ORM has no way of knowing > that this in-memory model object used to refer to a database row that has a > different primary key value. > > If this is not what you were expecting, you might want to re-think having > your models declare an explicit primary key, particularly if you are > expecting to allow changing the values. > > Karen --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Populating list_display with data from two models?
On 27 Feb, 01:56, Jamie Richard Wilson wrote: > I've extended the User model with a UserPofile model and have inline > editing working. Setup is something like this: > > class UserProfile(models.Model): > user = models.ForeignKey( > User, > unique=True, > ) > position = models.ForeignKey(Position) > ...etc... > > I need alist_displayin admin.py to display 'username', 'first_name', > 'last_name', and 'position'. I also need to be able to use list_filter > for 'position'. The problem I have is that the data is split between the > built-in User model and UserProfile model. Is there anyway for me to > combine data from two models into a single list view or will I need to > duplicate info such as first_name and last_name into the UserProfile > model and use that list_view? Try a UserProfileAdmin(admin.ModelAdmin) in admin.py and define a method that returns position. Like: class UserProfileAdmin(admin.ModelAdmin): def user_position(self, obj): return obj.get_profile().position list_display = ('username', 'first_name', 'last_name', 'user_position') then reregister your user admin.site.unregister(User) admin.site.register(User, UserProfileAdmin) --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---