Re: Dumping objects in templates
On Fri, Feb 8, 2008 at 6:46 AM, Gollum <[EMAIL PROTECTED]> wrote: > Is there any way to dump the whole object to html, for usual debugging > purposes. All I want is to see some objects whole structure, all field > values, child sets, etc. that are available for template. > I'm kind of new to python and django, but I have some cakePHP > experience and debug() function just that and I miss this kind of > functionality in django. Hi Gollum, The advantage of Python over PHP is that you have a REPL (the python interactive shell) and you don't need tricks like PHP's debug() for viewing stuff. My advice is that you read how to use the Python debugger (pdb); here's a short tutorial: http://www.ferg.org/papers/debugging_in_python.html And the complete reference: http://docs.python.org/lib/module-pdb.html You can use the pdb in you view function to see how your objects are constructed, what information you get from the request, and even modify any variable in-place or call any function that you desire. E.g.: def my_view(request): if request.method == "POST": import pdb; pdb.set_trace() # inspect your objects and environment # with pdb commands... You can put a pdb.set_trace() in any place you want; in a custom template tag, in a model or form method, in any part of the django code; any place where python code is being run. The flexibility and dynamism you get from the interactive debugger can not be matched by any amount of "print" statements in your code (or debug() calls) -- that was the PHP way but Python is a different animal. Regards, - Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Passing form initial values from one view to another?
Hi Dennis, On Jan 23, 2008 9:19 PM, Dennis <[EMAIL PROTECTED]> wrote: > follow up here though. Once this is implemented you end up with the > redirect URL looking something like this: > > http://mygreatwebsite.com/django_app/process/?newcontext=22 > > Which seems okay, but I also have a couple of other fields I'd like to > default, so when we add in more fields, the URL can become unwieldy: > > http://mygreatwebsite.com/django_app/process/?newcontext=22&newname=new%20string > It's not really necessary to send all the values back in the query string. You only need to send the id which you can use to fetch the object in your view and access all of its fields. For example, revisiting your process_task view: def process_task(request): if request.method == 'POST': I'm skipping this part else: if request.GET.get('newcontext'): # If there is a "newcontext" in the querystring, # we fetch it and use it to set up the initial # form values. context = get_object_or_404(Context, pk=request.GET['newcontext']) form = ProcessForm(initial={ 'context_id': context.id, 'context_name': context.name, 'context_foo': context.foo, 'context_bar': context.bar, }) else: # There were no new context # use a form without initial values. form = ProcessForm() return render_to_response('process.html', {'form': form}) If you haven't used "get_object_or_404" before, take a look here: http://www.djangoproject.com/documentation/shortcuts/ > > Which doesn't seem to be in line with django principles of readable > URL's. Thinking about this a little longer I thought it might be a > good idea to take a urls.py approach to the problem and create a new > entry such as: > Even though you could do that, personally I wouldn't. I think that an action or resource should be represented by a single URI. Your "process task" view is an action, which can accept different parameters to use as initial values but still, it is the same action. You would be unnecessarily duplicating code and complicating your urls.py file. Of course you might have seen URIs like these: /blog/entry/1/ /blog/entry/2/ /blog/entry/3/ Which makes sense because every blog entry is an unique resource which should be represented by a unique URI. Also, a blog is a public facing site and you would be interested in search engines indexing all your entries. Plus it makes it easier to tell someone over the phone how to get to a specific entry. In your case I'm guessing you are developing an application which requires a log-in before using it. Your application will be controlling the work flow from page to page, and you won't dictate someone over the phone to enter a long and confusing URI and parameters in their browser. Regards, - Jorge P.D. I noticed that your code is not consistently indented. Make sure you use the same number of spaces for each indentation level, preferably four, otherwise you will encounter problems in the future and it could be difficult to locate them if your indentation is all mixed up. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Passing form initial values from one view to another?
On Jan 20, 2008 11:58 PM, Dennis <[EMAIL PROTECTED]> wrote: > > This works from the standpoint of getting back to the "process.html" > template with the new Context object selected on the original form. > However, since this is using render_to_response instead of a redirect, > the URL on the user's browser still holds the "create_context" > location. So, when the user hits "submit" on the process.html page, > the form gets sent back to the "create_context" view and things don't > operate as expected (another context gets created rather than > submitting to the "process_task" view) > > The ideal way to do this would be to HttpResponseRedirect in place of > the "render_to_response" but this doesn't allow me to pass the form > object or any kind of dictionary representing the initial values. Is > there a way to do this? Or am I going about this in the wrong manner? > Hi Dennis, You are right that the ideal way would be to return an HttpResponseRedirect, and that's what I would do too. You can pass the id of the created context object as a parameter in the request back to the 'process_task' view. For example, your create_context view would look like this: def create_context( request ): if request.method == 'POST': form = CreateContextForm(request.POST) if form.is_valid(): # Do form processing here... # todo: clean_data is legacy, will need to be changed # to cleaned_data in next release. data = form.clean_data c = Context.objects.create( name=data['name'] ) # Pass the context id in the 'newcontext' parameter return HttpResponseRedirect('/process/?newcontext=%s' % c.id) else: form = CreateContextForm() return render_to_response('create_projctx.html', {'form':form}) Then your process_task view would be changed to check if there is a 'newcontext' parameter available in your request, in which case you use it to set the initial data of the form. def process_task(request): if request.method == 'POST': form = ProcessForm(request.POST) if form.is_valid(): # Do form processing here... # todo: clean_data is legacy, will need to be changed # to cleaned_data in next release. data = form.clean_data t = Task.objects.create( context=data['context'] , due_date=data['due_date'] ) return HttpResponseRedirect( request.META['HTTP_REFERER'] ) else: form = ProcessForm(initial={ 'context': request.GET.get('newcontext', None) }) return render_to_response('process.html', {'form': form}) The important part here is this: form = ProcessForm(initial={ 'context': request.GET.get('newcontext', None) }) You are setting an initial context depending on the value of the 'newcontext' request parameter, but because that parameter may not always be present you need to use the .get() method, the first parameter is the key to get from the dictionary and the second parameter is a value to return if the key is not found. In this case, when 'newcontext' is not found you'll get a None value back. After you create a new context on the other view and get redirected to process_task, there should be a value in the 'newcontext' request parameter, and the form will render with that context selected. Also note that this line: return HttpResponseRedirect( request.META['HTTP_REFERER'] ) will cause you problems because after creating a context, the referrer will be the /create_context/ page. Hope this helps. Regards, - Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: ANN: Django-fr.org is out!
On 6/22/07, Jeremy Dunck <[EMAIL PROTECTED]> wrote: > > Dice que estas en #django-es en freenode o un otra network? Estoy en > #django-es ahora. > > (Como se dice "network"?) > Se dice "red" Saludos! --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Interesting problem importing
On 4/7/07, Michael Newman <[EMAIL PROTECTED]> wrote: > > In the manage.py shell an error when I do the export > File "", line 1 > export DJANGO_SETTINGS_MODULE = speakeasy.settings > ^(arrow is under the E) > SyntaxError: invalid syntax > Hi Michael, I probably wasn't clear in my previous post. I described two ways to launch your python shell, one was to write "python manage.py shell", while the other was to define the environment variable in your bash shell (the export thingy). I see that you are already using "python manage.py shell", which means that you don't have to worry about setting the DJANGO_SETTINGS_MODULE environment variable; manage.py already did it for you. I apologize if I did things confusing before. Cheers, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Import, referencing modules across packages
On 4/6/07, Trey <[EMAIL PROTECTED]> wrote: > > Alright, I would like to reuse one of the forms, say Form1 inside of > the views for app2. So inside of the function I try this: > > def viewfunction(request): > from app1.forms import Form1 > > which fails pretty badly, I have also tried this: > > def viewfunction(request): > from projectpath.app1.forms import Form1 > > If anyone knows how to reuse classes from one application directory to > another please let me know your secrets :) > The "from project.app1.forms import Form1" line should work just fine, what is the error you are seeing?. Also, make sure that there is an "__init__.py" file in your /project/app1/ folder. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Interesting problem importing
On 4/6/07, Michael Newman <[EMAIL PROTECTED]> wrote: > > I am extremely new to programming, much less Django, but am working my > tail off trying to deploy a student alternative Webzine site. > > For the images I have been trying to use the nesh utils, > http://trac.studioquattro.biz/djangoutils/wiki/Thumbnail, because they > look perfect and a friend recommended them to me. I have tried > different methods to install the application and made the changes > talked about here, > http://groups.google.com/group/nesh-django-utils/browse_thread/thread/5129f1b17267abf5?hl=en > , but am still having problems. I am trying my hardest to break down > the code and figure out what could be going on. > > As I was going through the code, I opened a python shell to try to > import the functions. In order I did > > from django.conf import settings > from django.core.cache import get_cache > > and it raises an 'EnvironmentError: Environment Variable > DJANGO_SETTINGS_MODULE is undefined'. A quick search finds a few code > trac problems and a few fixes regarding this problem but none have > helped. > Just what the error says, you have to define the DJANGO_SETTINGS_MODULE environment variable. Assuming you have started a project, go to your project folder and in your shell run this: ~$ python manage.py shell It will set up the settings environment for you and fire up a python shell. If you still want to do it yourself, then what you need to do is something like this (in your shell of course): ~$ export DJANGO_SETTINGS_MODULE=myproject.settings ~$ python The 'export' thing is how you define an environment variable. I'm assuming here that your are using a Linux machine, if you are in Windows then you'll have to use the "python manage.py shell" command. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Serving Media through mod_proxy.
Hi David, On 2/27/07, David Abrahams <[EMAIL PROTECTED]> wrote: > > I'm running django with Apache/mod_python and serving media through > lighttpd. I have only one IP address, so lighttpd is running on port > 8081, but some of my clients are behind firewalls that block ports > other than 80. > > I'm planning to ditch Apache and run everything with lighttpd under > FastCGI, but I'm not ready to do that just yet just yet, so I'm > wondering if I can use mod_proxy to make it look like the media is > being served on port 80. My guess is that would defeat the purpose of > having separate servers, but I thought I'd check. > Take a look at this page under the section titled "Serving media files" http://www.djangoproject.com/documentation/modpython/ That way you can also serve your media files from your same Apache instance. Personally I've been using Lighttpd with FastCGI and it has been working great. In fact Lighttpd only redirect the traffic to the Django FastCGI instance, it doesn't have to load any python code itself so it is very light-weight and very good for serving media files. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: model referencing itself
Hi Aljosa, On 1/4/07, Aljosa Mohorovic <[EMAIL PROTECTED]> wrote: i'm trying to create a model which referencing itself and for this code i get this error: "name 'Chapter' is not defined" how do i do this or something similar? code: >>> from django.db import models class Chapter(models.Model): name = models.CharField(maxlength=200) content = models.TextField() prev = models.OneToOneField(Chapter) next = models.OneToOneField(Chapter) <<< Try with: prev = models.OneToOneField('self') next = models.OneToOneField('self') 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: problem with inclusion_tag
On 1/4/07, stoKes <[EMAIL PROTECTED]> wrote: On Jan 4, 12:10 pm, "Jorge Gajon" <[EMAIL PROTECTED]> wrote: > Hi Adam, > > On 1/3/07, stoKes <[EMAIL PROTECTED]> wrote: > > > base.html > > {% showmenu %} > > {% for service in services %} > > {{ > > service.name }} > > {% endfor %} > > > but receiving this error: > > > Exception Type: TemplateSyntaxError > > Exception Value:Invalid block tag: 'showmenu'Try putting {% load showmenu %} before the call to the tag, for example: > > {% load showmenu %} > {% showmenu %} > {% for service in services %} > {{service.name }} > {% endfor %} > > The {% load %} tag loads a .py file that contains your custom tags. In > this case it will try to load the file > /project/templatetags/showmenu.py > > If the .py file with your custom tags had a different name, for > example "mytags.py" then you would need to type a {% load mytags %} in > your template before using your custom tags. > Hey Jorge, I had tried that, however, this is the error I got : Exception Type: TemplateSyntaxError Exception Value:'showmenu' is not a valid tag library: Could not load template library from django.templatetags.showmenu, No module named showmenu i've created other templatetags before that loaded perfectly if i did it for a certain app, for example, /project/myapp/templatetags/tag.py but this is more of a global template tag so im not sure if my procedure in doing this is correct or not Oh I didn't noticed that little detail. But no, you can't have a "global" templatetag, your custom tags must be inside the 'templatetags' folder inside your app. This is what the documentation says about it: """The {% load %} tag looks at your INSTALLED_APPS setting and only allows the loading of template libraries within installed Django apps. This is a security feature: It allows you to host Python code for many template libraries on a single computer without enabling access to all of them for every Django installation. If you write a template library that isn't tied to any particular models/views, it's perfectly OK to have a Django app package that only contains a templatetags package.""" Hope it helps Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: problem with inclusion_tag
Hi Adam, On 1/3/07, stoKes <[EMAIL PROTECTED]> wrote: base.html {% showmenu %} {% for service in services %} {{ service.name }} {% endfor %} but receiving this error: Exception Type: TemplateSyntaxError Exception Value:Invalid block tag: 'showmenu' Try putting {% load showmenu %} before the call to the tag, for example: {% load showmenu %} {% showmenu %} {% for service in services %} {{service.name }} {% endfor %} The {% load %} tag loads a .py file that contains your custom tags. In this case it will try to load the file /project/templatetags/showmenu.py If the .py file with your custom tags had a different name, for example "mytags.py" then you would need to type a {% load mytags %} in your template before using your custom tags. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Curious error
On 1/1/07, Ramdas S <[EMAIL PROTECTED]> wrote: class billnumber(models.Model): date = models.DateTimeField(auto_now_add=True, primary_key = True) def __str__(self): return self.id You added the 'primary_key' attribute to your date field, therefore your model will not have an 'id' field which you are trying to access in __str__(). Remove the 'primary_key' attribute from the date field in your model, or else, modify your __str__() method. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Can't get my URLs right.
On 12/27/06, Jason <[EMAIL PROTECTED]> wrote: So now that I add an about page, as www.foo.com/about what I get is a bunch of 404 errors because it's looking form my CSS and images in: /about/css/styles.css (should be /css/styles.css) and images references in the CSS in about/css/i/abc.png (should be i/abc.png). I don't really want to keep recurring and linking my file system to make this work. Hi Jason, You need to write absolute urls in your html, for example, instead of: You have to: Notice the slash at the beginning of "/css/styles.css". Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Extrange behavior with get 'self' FK in admin view
Hi, On 12/20/06, ElGranAzul <[EMAIL PROTECTED]> wrote: Hi, i've and extrange behavior with admin views with the following code: I copied your code to a test project, added the missing Country and Island objects and tried it but I could not reproduce your problem, everything works fine here. I added some objects and the list view works fine, the detail view also works fine. It's probable that the error lies in one of the Country or Island objects. Also, I did re-indent your code when I copied it here. You should re-check your indentation, I can see that the body of __parents_repr has a higher indentation that the rest of the code, although it shouldn't really matter, you should probably check it just to be sure. Regards, Jorge class Subdivision(models.Model): code = models.CharField(_('Code'), maxlength=10, primary_key=True) name = models.CharField(_('Name'), maxlength=100, core=True) stype = models.CharField(_('Type'), maxlength=3, choices=COUNTRY_SUBDIVISION_TYPE) country = models.ForeignKey(Country, verbose_name=_('Country')) island = models.ForeignKey(Island, verbose_name=_('Island'), blank=True, null=True) parent = models.ForeignKey('self', related_name="children", verbose_name=_('Parent Subdivision'), blank=True, null=True) lat = models.FloatField(_('Latitude'), max_digits=9, decimal_places=6, blank=True, null=True) lon = models.FloatField(_('Longitude'), max_digits=9, decimal_places=6, blank=True, null=True) def __str__(self): parent = self._parents_repr() if parent: return ('%s (%s of %s, %s)') % (self.name, self.get_stype_display(), parent, self.country) else: return ('%s (%s of %s)') % (self.name, self.get_stype_display(), self.country) __str__.short_description = _("Descipcion") def _recurse_for_parents(self, cat_obj): p_list = [] if cat_obj.parent_id: p = cat_obj.parent p_list.append([p.name,p.stype]) more = self._recurse_for_parents(p) p_list.extend(more) if cat_obj == self and p_list: p_list.reverse() return p_list def _parents_repr(self): p_list = self._recurse_for_parents(self) if len(p_list) >= 1: p = p_list.pop() p_list = p[0] else: p_list = '' return p_list class Meta: verbose_name = _('Subdivision') verbose_name_plural = _('Subdivisions') class Admin: list_display = ('code','name','island','__str__') list_filter = ['country','stype'] search_fields = ['code','name'] The problem is that wehn i try to edit an object and call self._parents_repr() in __str__ the admin views raise an 404 error saying that cannot find a model with this code, but if i remove the self._parents_repr() it works ok. In shell the str output works good, and in admin list. Is it an admin views error? --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: dynamic query key asignment
Hi there k1000, On 12/21/06, k1000 <[EMAIL PROTECTED]> wrote: Is there any way to create dynamically key ( 'thiskey_exact' ) in query object. eg: Object.objects.filter(thiskey_exact = 'something') I'll paste here an example from one project I have here: Actividad.objects.filter(nombre__icontains='fabri') [] dyn_key = '%s__icontains' % 'nombre' kwargs = {} # a dictionary kwargs[dyn_key] = 'fabri' # the value to the key kwargs {'nombre__icontains': 'fabri'} Actividad.objects.filter(**kwargs) [] Hope it helps. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Request data in inclusion tag
Hi Eugene, On 12/21/06, Eugene Pyvovarov <[EMAIL PROTECTED]> wrote: Look, I have a little problem. I need to put on the page shopping cart icon and quantity of elements in cart. I make custom inclusion tag. But now I have a problem - I can not access request object with session data(I store quantity in user's session). How can i do this thing? Thanks You need to pass a RequestContext from your views to your template, take a look at this: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext Your inclusion tag will also need a second parameter called 'takes_context' set to True, ie: mytag = register.inclusion_tag('template.html', takes_context=True)(mytag) See: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext/ Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Admin login problem
On 12/12/06, Yatla <[EMAIL PROTECTED]> wrote: > > Newbie here - saw that the same question was asked earlier but not > answered, and the post was locked so I could not reply. > > I have a Django site in a subdirectory as follows (via fcgi) - (using > ver 0.96 pre via svn) > > http://mydomain.com/dj > > When I go into the Admin area as follows > > http://mydomain.com/dj/Admin/ > > The login form that comes up has action="/admin/" (not "/dj/admin"), so > the post goes to > > http://mydomain.com/admin > > which is not the Django site. Somehow the /dg/ subdirectory info is > not prefixed to the form action. Is there a configuration with the > main site prefix that I'm missing somwhere, I ony see path to media to > be set in tte seetings? > Hi Yatla, Are you using an .htaccess file? I have a site on Dreamhost in which my Django app live under a sub-url like this: http://mydomain.com/galeria/ In my .htaccess file (in the 'galeria' folder of the domain) I have the following rules: RewriteEngine On RewriteRule ^(media/.*)$ - [L] RewriteCond %{REQUEST_URI} !(django.fcgi) RewriteRule ^(.*)$ django.fcgi/galeria/$1 [L] Remember that in your urls.py file you will need to include the admin urls like this: (r'^galeria/admin/', include('django.contrib.admin.urls')), Hope it helps. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Validation 3 steep complicate form
Hi, On 12/3/06, GvaderTh <[EMAIL PROTECTED]> wrote: > > Hello All. I read django documentation about forms, had seek internet > and didn't found solution for situation like this: I have order form > divided to 3 steeps, after every step should be validation and if > validation is succesfull, user can fill form for next-step. Form for > every step doesn't map to database table, or object, I think that only > filled succesfully 3 step, the result will be a new object. What is the > best way to do this? At the beggining I thought that after every step, > value after validation I will hold in session and at the end I made > final object. But for now I don't know how to write template for this > task, and how to do validation for this. Any help? Please > Thanks > G. > Since the first two forms doesn't map to a database object, you will need to create custom forms and manipulators. Take a look at: http://www.djangoproject.com/documentation/forms/#custom-forms-and-manipulators Although, the way to create and use custom forms is going to change soon. Just be aware of that. You can create three views, one for each step. In the first view, create a custom manipulator to handle and validate the data that is entered in that first view. If the data is correct, use sessions to store a flag that indicates that the user has entered the information correctly and redirect him to the next view. In the next view you would then check in the session that the flag for the previous view is set. If you will later need the supplied information then store it in the session too, do not use hidden fields to carry it over different views. Sessions documentation: http://www.djangoproject.com/documentation/sessions/ Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Setting checkbox to check as default value
Hi Jeff, On 12/2/06, jeffhg58 <[EMAIL PROTECTED]> wrote: > I have a custom manipulator and I am trying to set the checkbox default > to checked. > > For example, my field name is: > > forms.CheckboxField(field_name="current"), Pass a 'checked_by_default' argument to the CheckboxField constructor, like this: forms.CheckboxField(field_name="current", checked_by_default=True), Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Calling Methods from Admin
On 12/2/06, Beau Hartshorne <[EMAIL PROTECTED]> wrote: > > What's the best way make a method call from Django's admin? I'd like > to set up a link or button that re-sends emails to users who've lost > them to the Internet or spam traps or whatever. > Well, I'm not sure what is the best way to do it, but I'll explain how I would do it. First, you need to display the link that will trigger the process. For example, if you have this model in your app's models.py file: <<< class Person(models.Model): name = models.CharField(maxlength=80) email = models.EmailField() class Admin: list_display = ('name', 'email', 'reminder_link') def reminder_link(self): return 'Send reminder' % self.id reminder_link.allow_tags = True >>> There you are telling the admin interface to display three columns, the 'name', 'email' and a 'reminder_link' property which will cause it to call a method of that name on the object. Therefore you need to define that method, which simply returns an HTML portion that should display a link. You'll need to set an 'allow_tags' property to the method so that the admin interface does not escape the HTML that it returns. Adjust the link that the 'reminder_link' method returns to better fit your project. Next, we'll have to handle any request to '/admin/person/sendreminder/' with a custom view. You'll have to add an url pattern to your urls.py file: <<< urlpatterns = patterns('', (r'^admin/person/sendreminder/(\d+)/$', 'myapp.views.send_reminder'), (r'^admin/', include('django.contrib.admin.urls')), your other urls ) >>> You must add the handler for '/admin/person/sendreminder/' before the default 'admin/' pattern, otherwise the included admin would try to handle it and would spit an error. Now you need to create the view that will actually do the work of sending the reminder. In your views.py file you will define the 'send_reminder' view: <<< from django.core.mail import send_mail def send_reminder(request, person_id): person = get_object_or_404(Person, pk=person_id) subject = 'Your name reminder' body = 'Hey, your name is %s' % person.name sender = '[EMAIL PROTECTED]' recipient = [person.email] send_mail(subject, body, sender, recipient) return render_to_response('reminder_sent.html') >>> That function send a simple email to the user indicated by the 'person_id' parameter. You would then create 'reminder_sent.html' template and display a confirmation message. The only thing left to do is to make sure that only a staff user can access the '/admin/person/sendreminder/' url. To do that you need to decorate your view with a 'staff_member_required' decorator like this: <<< from django.contrib.admin.views.decorators import staff_member_required from django.views.decorators.cache import never_cache def send_reminder(request, person_id): snip return render_to_response('reminder_sent.html') send_reminder = staff_member_required(never_cache(send_reminder)) >>> And that's it. Hope it can help. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Help with Contact Form
On 11/30/06, luxagraf <[EMAIL PROTECTED]> wrote: > > Hello all I have a quick question, I just whipped up a custom > manipulator for a contact form and, following the suggestion in the > django docs, I'm using a > > HttpResponseRedirect("/contact/thankyou/") > > to get rid of the post data, but what I'd like to display at that > redirect url is a copy of the message the user sent... but I can't > figure out how to do that... > > is there a way to do something like this: > > HttpResponseRedirect("/contact/thankyou/" > extra_context={'my_form_data': data_as_list}) > You cannot do that because HttpResponseRedirect causes the browser to navigate to another URL, it does not render anything at all. Think of it as if the user manually typed the "/contact/thankyou/" URL in their browser. > note that I'm not storing the message, there is no model to query to, > I thought of using a cookie, but the seems unnecessary... > Since you are not storing the data, then I can only thing of two solutions. One is to pass that data on the query string of the "thankyou" url, and get it from request.GET on that view. The other option is, as you said, to use sessions. I would personally use sessions, or store the data into the database. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Accessing request and session objects from templates
Hi, On 11/3/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I am wondering if there is a way to access request data and session object > directly from Django templates, in the same way as {{ user }} for instance. > I must admit I'm a bit lost with template context processors and so on... You need to activate the "django.core.context_processors.request" context processor. To do that you should add the following to your settings.py file: TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.request', ) Then, to actually have your context processors activated during a template rendering, you must pass a RequestContext as the context for your template. In other words, when you are returning a render_to_response() in your view you should do it like this: def my_view(request): # do your stuff return render_to_response('my_template.html', my_data, context_instance=RequestContext(request) ) Take a look at the documentation here: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext Hope it helps. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: setting and using an object variable without using a field
On 11/3/06, Rob Slotboom <[EMAIL PROTECTED]> wrote: > And. it's working. > Just one question: Is this the right way to do such things? > I don't see any problem with it, as long as the template doesn't care where "voted_by_remote_add" comes from or how it is constructed. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Error importing settings.py
On 10/31/06, sansmojo <[EMAIL PROTECTED]> wrote: > > Hello all! My server admin has set up an apache/mod_python server for > me, but we keep getting the following error: > http://paste.e-scribe.com/2490/ > > Our apache config is here: http://paste.e-scribe.com/2491/ > You probably only need to change this line in your apache config: SetEnv DJANGO_SETTINGS_MODULE /var/www/closed/ce/settings.py for this one: SetEnv DJANGO_SETTINGS_MODULE ce.settings Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Custom manipulator
On 10/28/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > 1) {{form.teacher}} doesn't render the actual teacher assigned to that > course but just the first in the list of teachers. > I'm guessing here since I don't have open any project to test it on, but I suspect that is because you are initializing your form data with this: new_data = dict(code=course.code, name=course.name, description=course.description, teacher=course.teacher, assistant=course.assistant) which makes new_data['teacher'] contain a teacher object when you actually only need a value. You could change that to: teacher=str(course.teacher.id) Another thing, maybe you are doing more things that you didn't included in the pasted code, but I don't see any need for a custom manipulator there, and I would suggest you to use the default generated manipulators. Your code could be more simpler, like this: def course_edit(request, course_id): try: manipulator = Course.ChangeManipulator(course_id) except: raise Http404 course = manipulator.original_object new_data = {} errors = {} if request.POST: new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: manipulator.do_html2python(new_data) manipulator.save(new_data) return HttpResponseRedirect("/course_edit/%s" % course_id) else: new_data = manipulator.flatten_data() form = forms.FormWrapper(manipulator, new_data, errors) return render_to_response("course.html", {'form'=form}) > 2) In the manipulator save() method i have to refer to model fields > with course.teacher_id. Shouldn't i be able to just do course.teacher > without instantiating a teacher object? > No, course.teacher must be a Teacher object. And since you are using a custom manipulator, you'll need to fetch that object in the save() method. Or, as you already noted, you can use course.teacher_id and assign it a valid id. Cheers, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Generating a choices set from data
On 10/27/06, Russell Keith-Magee <[EMAIL PROTECTED]> wrote: > > On 10/26/06, Ice9 <[EMAIL PROTECTED]> wrote: > > > > Hi, I'm kinda new to django, and I ran into a problem > > I'm making a cutom form, and one of the field I want it to be > > SelectField. the problem is I dont want to hard code the choices in, I > > want to generate a set of choice I can use from the data i already > > have. > > For example, I have a lot of polls, and I want the choices to be all > > the polls posted by user root. How would I come to do that? > > Sounds like you need 'limit_choices_to' on a Foreign Key. Add a > Foreign Key on Choices to the Poll model; use the limit_choices_to > argument on the ForeignKey defintion to filter out those choices you > don't want. > Russell's answer is your best option in this case and is also cleaner. However, if you still want to know how to generate the choices list for your SelectField, you can do something like this: class MyManipulator(forms.Manipulator): def __init__(self): filtered_data = MyModel.objects.filter(... some condition...) my_choices = [(obj.id, obj) for obj in filtered_data] self.fields = ( forms.SelectField(field_name='name', choices=my_choices), ) Basically you use a list generation expression to generate a list of tuples, each tuple must contain two elements, the first element is the choice value (e.g. the id of the object) and the second element is the label that you want to display in the select field for that value (in this example we assume that obj has an appropriate __str__() method). Hope it helps. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: template and special character problem
On 9/18/06, Phil <[EMAIL PROTECTED]> wrote: > I tried what you suggested (replace my meta http-equiv by your version) > and it does no good )c: Sorry to hear that Phil, I don't know what else to suggest :( It is really weird that it works when you duplicate the content-type line though. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: template and special character problem
On 9/16/06, Phil <[EMAIL PROTECTED]> wrote: > In the base.html template I added in the section a {% block > extrahead %}{% endblock %}. > And in the index.html template I added {% block extrahead %} http-equiv="content-type" content="application/xhtml+xml; > charset=UTF-8" /> {% endblock %} It is really strange that you need to duplicate your content-type to make it work. I believe your problem lies in how the browser is interpreting your html file and not in Django. Also, what happens if you instead specify your content-type in your base.html file like this? There are two differences, Content-Type (first letters are uppercase) and the mime type is "text/html" instead of "application/xhtml+xml" By default, Django serves the Content-Type header (in the HTTP response headers) like that. See DEFAULT_CHARSET and DEFAULT_CONTENT_TYPE: http://www.djangoproject.com/documentation/settings/#default-charset > I plan to debug this to see why Django doesn't seem to know what is the > encoding of the index.html template. If your text editor is correctly writing your files in UTF-8 and you didn't changed the DEFAULT_CHARSET setting in your settings file, then there shouldn't be any problem with how Django reads your templates. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: template and special character problem
Hi, On 9/12/06, Phil <[EMAIL PROTECTED]> wrote: > When I render index.html, the special character from base.html are > rendered normaly but the ones from index.html are shown as '?'. Make sure that the editor you are using is writing your files to disk with the correct encoding. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: foreignKey + manipulator...performance problem, SOLVED
Hi, On 8/31/06, Gábor Farkas <[EMAIL PROTECTED]> wrote: > you need to use the raw_id_admin = True flag in the ForeignKey, > and all will be fine. Great!, Thank you Gábor :) I was having the same problem too. Cheers, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: foreignKey + manipulator...performance problem
On 9/2/06, Jorge Gajon <[EMAIL PROTECTED]> wrote: > I think this should be put on a ticket as an enhancement, the > manipulator should load the foreign data only (and just only) when you > actually put a {{ form.foreign_field }} in your template and the html > select tag needs to be rendered. Or maybe just wait for the impending removal of manipulators :) --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: foreignKey + manipulator...performance problem
Hi, On 8/30/06, gabor <[EMAIL PROTECTED]> wrote: > everything is ok, until you call > > Owner.AddManipulator()... this will take a long time. I got this same problem yesterday, however I'm short in time so I couldn't look deeper on what to do. I ended passing follow={'field':False} and then saving the object manually but I don't like that and will try to do something better later. I think this should be put on a ticket as an enhancement, the manipulator should load the foreign data only (and just only) when you actually put a {{ form.foreign_field }} in your template and the html select tag needs to be rendered. I can't write up the ticket because I need to go in 5 minutes :( Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Having trouble with views
Many people come to Django without having knowledge of Python before, and that's perfectly fine!, but you must be aware that it is DOUBLE hard, and you must double your efforts to learn Django and Python alongside. My recommendation (and Malcolm also said it) is that you first get to know Python better and then tackle Django, one at a time. It will make things easier in the long run, and you will be able to better understand how Django works and why. Here are some places to start: http://pytut.infogami.com/ http://www.diveintopython.org/ http://www.awaretek.com/tutorials.html#begin http://www.ferg.org/papers/debugging_in_python.html Trust me, once you feel comfortable writing and debugging Python programs, getting Django to do what you want it to do will be really easy. Cheers, Jorge On 8/11/06, Tomas Jacobsen <[EMAIL PROTECTED]> wrote: > No problem. Thank you for all your help! I really appreciate what you > have done. Without your help, I probably would have given up on django > a long time ago. I will try to read more of the tutorials, It's just > that it isen't that easy to find a tutorial that covers what Im trying > to do. > > Best regards, > Tomas > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Scandinavian characters in .po files and timezones
Hi, Take notice that there is also a 'fileencoding' setting in vim. When you create a new file in vim, 'fileencoding' will not be set and so it will take the current value from 'encoding'. When you open an existing file, vim will try to determine its encoding and set 'fileencoding' accordingly. But be aware that if you change the 'encoding' the 'fileencoding' variable will not be affected. If you want to actually change the encoding of an existing file you must change the variable 'fileencoding' and save (:w) the file. Look at :help fileencoding and :help encodingfor more details. You could also take a look at this script: http://www.vim.org/scripts/script.php?script_id=789 Cheers, Jorge On 7/30/06, Mikko Nylén <[EMAIL PROTECTED]> wrote: > > Thanks for all answers. I was able to fix the problem by starting over with > the django.po. May be the problem was that when I did start working with the > file, I didn't have set encoding=utf-8 and when I turned it on in the middle, > Vim didn't convert the characters to UTF-8. > > - Mikko Nylén > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: debugging xmlhttprequest POST's is a PAIN! Need help.
Hi, On 7/14/06, Jeremy Dunck <[EMAIL PROTECTED]> wrote: > Run with the built-in server and put this in your view code: > > import pdb > pdb.set_trace() > +1 for using pdb. It will save you a lot of time debugging your code. And if you haven't used pdb, check out this tutorial: http://www.ferg.org/papers/debugging_in_python.html Highly recommended! --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Custom Manipulator problem
Hi again, I rushed with my previous email. Why don't you use the generated manipulator from the model instead of writing your own? You only need to change this line: manipulator = EntryManipulator() with this line: manipulator = Entry.AddManipulator() that should work. Then there's no need to write the custom manipulator. Cheers, Jorge On 7/14/06, Robert <[EMAIL PROTECTED]> wrote: > > Hello, > > When using custom Manipulator (which in fact does nothing.. I've cut > some additional custom validation here) I'm getting error as follows: > > Traceback (most recent call last): > File > "/usr/local/lib/python2.4/site-packages/Django-0.95-py2.4.egg/django/core/handlers/base.py" > in get_response > 74. response = callback(request, *callback_args, **callback_kwargs) > File "/usr/local/www/data/django/projects/pbook/../pbook/book/views.py" > in create_entry > 23. new_entry = manipulator.save(new_data) > File > "/usr/local/lib/python2.4/site-packages/Django-0.95-py2.4.egg/django/forms/__init__.py" > in save > 92. raise NotImplementedError > > NotImplementedError at / > - > > Python 2.4.2, DB: SQLite, svn from trunk as of July 13th > > Error occurs on POST when submitting, I am able to see & fill in the > form. > > This is my code: > > ---> book/models.py > from django.db import models > > class Entry(models.Model): > name = models.CharField(blank=False, maxlength=30) > last = models.CharField(blank=False, maxlength=50) > nr = models.IntegerField(unique=True, blank=True, maxlength=10) > nr_mobile = models.IntegerField(unique=True, blank=True, > maxlength=9) > > def __str__(self): > return self.name > > class Admin: > pass > > --> book/views.py > from django.shortcuts import render_to_response > from django.core import validators > from django import forms > from pbook.book.models import Entry > from django.http import Http404, HttpResponse, HttpResponseRedirect > > def create_entry(request): > manipulator = EntryManipulator() > > if request.POST: > new_data = request.POST.copy() > > errors = manipulator.get_validation_errors(new_data) > > if not errors: > manipulator.do_html2python(new_data) > new_entry = manipulator.save(new_data) > return HttpResponse("Entry created: %s" % new_entry) > else: > errors = new_data = {} > > form = forms.FormWrapper(manipulator, new_data, errors) > return render_to_response('book/entry_form.html', {'form': form }) > > class EntryManipulator(forms.Manipulator): > def __init__(self): > self.fields = ( > forms.TextField(field_name='name', > is_required=True, maxlength=30), > forms.TextField(field_name='last', > is_required=True, maxlength=50), > forms.IntegerField(field_name='nr', > maxlength=10), > forms.IntegerField(field_name='nr_mobile', > maxlength=9), > ) > > ---> urls.py > from django.conf.urls.defaults import * > from pbook.book.models import Entry > > urlpatterns = patterns('', > (r'^$', 'pbook.book.views.create_entry'), > (r'^admin/', include('django.contrib.admin.urls')), > ) > > ---> templates/book/entry_form.html > {% if form.has_errors %} > Please correct the following error{{ form.error_dict|pluralize > }}: > {% endif %} > > > > Name: {{ form.name }} > {% if form.name.errors %}*** {{ form.name.errors|join:", " }}{% > endif %} > > > Last: {{ form.last }} > {% if form.last.errors %}*** {{ form.last.errors|join:", " }}{% > endif %} > > > Phone nr: {{ form.nr }} > {% if form.nr.errors %}*** {{ form.nr.errors|join:", " }}{% endif > %} > > > Mobile nr: {{ form.nr_mobile }} > {% if form.nr_mobile.errors %}*** {{ form.nr_mobile.errors|join:", > " }}{% endif %} > > > > > Thanks, > Robert > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Custom Manipulator problem
Hi, You need to implement the save() method in your custom manipulator. Cheers On 7/14/06, Robert <[EMAIL PROTECTED]> wrote: > > Hello, > > When using custom Manipulator (which in fact does nothing.. I've cut > some additional custom validation here) I'm getting error as follows: > > Traceback (most recent call last): > File > "/usr/local/lib/python2.4/site-packages/Django-0.95-py2.4.egg/django/core/handlers/base.py" > in get_response > 74. response = callback(request, *callback_args, **callback_kwargs) > File "/usr/local/www/data/django/projects/pbook/../pbook/book/views.py" > in create_entry > 23. new_entry = manipulator.save(new_data) > File > "/usr/local/lib/python2.4/site-packages/Django-0.95-py2.4.egg/django/forms/__init__.py" > in save > 92. raise NotImplementedError > > NotImplementedError at / > - > > Python 2.4.2, DB: SQLite, svn from trunk as of July 13th > > Error occurs on POST when submitting, I am able to see & fill in the > form. > > This is my code: > > ---> book/models.py > from django.db import models > > class Entry(models.Model): > name = models.CharField(blank=False, maxlength=30) > last = models.CharField(blank=False, maxlength=50) > nr = models.IntegerField(unique=True, blank=True, maxlength=10) > nr_mobile = models.IntegerField(unique=True, blank=True, > maxlength=9) > > def __str__(self): > return self.name > > class Admin: > pass > > --> book/views.py > from django.shortcuts import render_to_response > from django.core import validators > from django import forms > from pbook.book.models import Entry > from django.http import Http404, HttpResponse, HttpResponseRedirect > > def create_entry(request): > manipulator = EntryManipulator() > > if request.POST: > new_data = request.POST.copy() > > errors = manipulator.get_validation_errors(new_data) > > if not errors: > manipulator.do_html2python(new_data) > new_entry = manipulator.save(new_data) > return HttpResponse("Entry created: %s" % new_entry) > else: > errors = new_data = {} > > form = forms.FormWrapper(manipulator, new_data, errors) > return render_to_response('book/entry_form.html', {'form': form }) > > class EntryManipulator(forms.Manipulator): > def __init__(self): > self.fields = ( > forms.TextField(field_name='name', > is_required=True, maxlength=30), > forms.TextField(field_name='last', > is_required=True, maxlength=50), > forms.IntegerField(field_name='nr', > maxlength=10), > forms.IntegerField(field_name='nr_mobile', > maxlength=9), > ) > > ---> urls.py > from django.conf.urls.defaults import * > from pbook.book.models import Entry > > urlpatterns = patterns('', > (r'^$', 'pbook.book.views.create_entry'), > (r'^admin/', include('django.contrib.admin.urls')), > ) > > ---> templates/book/entry_form.html > {% if form.has_errors %} > Please correct the following error{{ form.error_dict|pluralize > }}: > {% endif %} > > > > Name: {{ form.name }} > {% if form.name.errors %}*** {{ form.name.errors|join:", " }}{% > endif %} > > > Last: {{ form.last }} > {% if form.last.errors %}*** {{ form.last.errors|join:", " }}{% > endif %} > > > Phone nr: {{ form.nr }} > {% if form.nr.errors %}*** {{ form.nr.errors|join:", " }}{% endif > %} > > > Mobile nr: {{ form.nr_mobile }} > {% if form.nr_mobile.errors %}*** {{ form.nr_mobile.errors|join:", > " }}{% endif %} > > > > > Thanks, > Robert > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Non iterable argument
Hi, You are calling manipulator.do_html2python() before the call to get_validation_errors() The correct thing is to call do_html2python() after you have validated the data and there are no errors. It should look like this: errors = manipulator.get_validation_errors(new_data) print errors if not errors: print "noerrors" manipulator.do_html2python(new_data) print new_data['owner'] Cheers, Jorge On 7/13/06, Lucas Vogelsang <[EMAIL PROTECTED]> wrote: > > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > Hi, > > I have an integer in my model: > rating= models.IntegerField(null=true, blank=true) > And I create my Add form for the class like as described in the > manipulator doc with a manipulator[1]. As expected, { form.rating } > creates an input field. However, when I try to submit the form I get > the error "Non iterable argument", see [2]. > > Anybody can help me out with this? > > [1] http://wservices.ch/~lucas/ablage/views.py > [2] http://wservices.ch/~lucas/ablage/error.html > > regards, lucas > -BEGIN PGP SIGNATURE- > Version: GnuPG v1.4.3 (GNU/Linux) > Comment: Signed with GPG & Enigmail - see http://www.vincisolutoins.ch/pgp/ > > iD8DBQFEtn4P3RQ/RpGW2HgRAn9qAJ9btgJXt34o2aQWnSiXwRkmwVnOBwCgsmrO > yDHFpzWwFpM2jN7RlXmHyYY= > =iBZU > -END PGP SIGNATURE- > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Please fix my ugly code
Hi again Carlos, I suggested this change in your code: > results = Vozilo.objects.all() > if selected_model_id != 0: > results = results.filter(model_id__exact=selected_model_id) > if selected_gorivo_id != 0: > results.extend(results.filter(gorivo_id__exact=selected_gorivo_id)) > But I'm totally wrong there. Your original code should be fine, because you were chaining the filters. The 'extends' is not necessary and in fact it is wrong. I also realized that the filter logic in the code that I proposed is wrong. With that code you would get a list of cars that match the specified model, along with all the cars that match the gorivo type (regardless of model). The correct thing is to chain the filters like you did in your original code. This should work, I tested it with a model I have here. results = Vozilo.objects.all() if model: results = results.filter(model=model) if gorivo: results = results.filter(gorivo=gorivo) I'm sorry if I caused any confusion and for not paying more attention to that filtering part :) Cheers, Jorge On 7/13/06, Jorge Gajon <[EMAIL PROTECTED]> wrote: > Hi Carlos, > > I think your code is going good so far. Of course I'm not a guru but I > think your code is fine. Is there something that you don't feel > comfortable with? With respect to adding the results of both filters, > you need to extend the results of the first results (if any), like > this: > > results = Vozilo.objects.all() > if selected_model_id != 0: > results = results.filter(model_id__exact=selected_model_id) > if selected_gorivo_id != 0: > results.extend(results.filter(gorivo_id__exact=selected_gorivo_id)) > > > > If I were to code that view I would use a custom manipulator and it > would end up something like the following. But PLEASE, PLEASE, be > aware that it's just my personal way of doing things, I am no one to > tell you how to do things. > > class FilterResultsManipulator(forms.Manipulator): > def __init__(self): > model_choices = [(m.id, m) for m in Model.objects.all()] > gorivo_choices = [(g.id, g) for g in > Gorivo.objects.all().order_by('opis')] > self.fields = ( > forms.SelectField(field_name='model', choices=model_choices), > forms.SelectField(field_name='gorivo', choices=gorivo_choices), > ) > > def home(request): > results = [] > filter_manipulator = FilterResultsManipulator() > filter_data = {} > > if request.POST: > filter_data = request.POST.copy() > > model = None > gorivo = None > if filter_data.get('model'): > model = get_object_or_404(Model, pk=filter_data['model']) > if filter_data.get('gorivo'): > gorivo = get_object_or_404(Gorivo, pk=filter_data['gorivo']) > > if model: > results = Vozilo.objects.filter(model=model) > if gorivo: > results.extend(Vozilo.objects.filter(gorivo=gorivo)) > else: > results = Vozilo.objects.order_by('?')[:5] > > filter_form = forms.FormWrapper(filter_manipulator, filter_data, {}) > > return render_to_response('cars/home.html', { > 'results': results, > 'filter_form': filter_form, > }) > > And the template you only need to display the form fields. > > > Search by: > Model: {{ filter_form.model }} > Gorivo: {{ filter_form.gorivo }} > > > > > The custom manipulator and associated form wrapper takes care of > displaying the select fields in your form and maintaining the selected > option between posted pages. The use of the utility > get_object_or_404() frees you of worrying if the incoming data is > invalid or malformed, if it is a 404 exception will be raised and the > user will get a 404 page. > > If you have questions about the above code feel free to ask. > > Cheers, > Jorge > > > > On 7/13/06, Carlos Yoder <[EMAIL PROTECTED]> wrote: > > > > Hello people, my ongoing adventures in firstdjangoappland continue thus: > > > > I'm putting together a simple search app for a car project. On entry, > > user sees a list of 5 random cars. He can use up to two comboboxes to > > filter the results (car model and fuel type). > > > > This is what I've come up with on my home() view, so far, and it looks > > really ugly. > > > > def home(request): > > > > results = {} > > > > # these 2 guys are the filters > > mo
Re: Please fix my ugly code
Hi Carlos, I think your code is going good so far. Of course I'm not a guru but I think your code is fine. Is there something that you don't feel comfortable with? With respect to adding the results of both filters, you need to extend the results of the first results (if any), like this: results = Vozilo.objects.all() if selected_model_id != 0: results = results.filter(model_id__exact=selected_model_id) if selected_gorivo_id != 0: results.extend(results.filter(gorivo_id__exact=selected_gorivo_id)) If I were to code that view I would use a custom manipulator and it would end up something like the following. But PLEASE, PLEASE, be aware that it's just my personal way of doing things, I am no one to tell you how to do things. class FilterResultsManipulator(forms.Manipulator): def __init__(self): model_choices = [(m.id, m) for m in Model.objects.all()] gorivo_choices = [(g.id, g) for g in Gorivo.objects.all().order_by('opis')] self.fields = ( forms.SelectField(field_name='model', choices=model_choices), forms.SelectField(field_name='gorivo', choices=gorivo_choices), ) def home(request): results = [] filter_manipulator = FilterResultsManipulator() filter_data = {} if request.POST: filter_data = request.POST.copy() model = None gorivo = None if filter_data.get('model'): model = get_object_or_404(Model, pk=filter_data['model']) if filter_data.get('gorivo'): gorivo = get_object_or_404(Gorivo, pk=filter_data['gorivo']) if model: results = Vozilo.objects.filter(model=model) if gorivo: results.extend(Vozilo.objects.filter(gorivo=gorivo)) else: results = Vozilo.objects.order_by('?')[:5] filter_form = forms.FormWrapper(filter_manipulator, filter_data, {}) return render_to_response('cars/home.html', { 'results': results, 'filter_form': filter_form, }) And the template you only need to display the form fields. Search by: Model: {{ filter_form.model }} Gorivo: {{ filter_form.gorivo }} The custom manipulator and associated form wrapper takes care of displaying the select fields in your form and maintaining the selected option between posted pages. The use of the utility get_object_or_404() frees you of worrying if the incoming data is invalid or malformed, if it is a 404 exception will be raised and the user will get a 404 page. If you have questions about the above code feel free to ask. Cheers, Jorge On 7/13/06, Carlos Yoder <[EMAIL PROTECTED]> wrote: > > Hello people, my ongoing adventures in firstdjangoappland continue thus: > > I'm putting together a simple search app for a car project. On entry, > user sees a list of 5 random cars. He can use up to two comboboxes to > filter the results (car model and fuel type). > > This is what I've come up with on my home() view, so far, and it looks > really ugly. > > def home(request): > > results = {} > > # these 2 guys are the filters > model_list = Model.objects.all() > gorivo_list = Gorivo.objects.all().order_by('opis') > > selected_model_id = 0 > selected_gorivo_id = 0 > > if request.POST: > # this handles 'SELECTED' attribute on comboboxes > try: > selected_model_id = int(request.POST['model_id']) > except: > pass > try: > selected_gorivo_id = int(request.POST['gorivo_id']) > except: > pass > > # and this should take care of the filtering... but I'm > stumped really > # both filters should add up > results = Vozilo.objects.all() > if selected_model_id != 0: > results = > results.filter(model_id__exact=selected_model_id) > if selected_gorivo_id != 0: > results = > results.filter(gorivo_id__exact=selected_gorivo_id) > else: > # no POST, we show 5 random cars. > results = Vozilo.objects.order_by('?')[:5] > > return render_to_response('cars/home.html', { > 'model_list':model_list, > 'gorivo_list':gorivo_list, > 'selected_model_id':selected_model_id, > 'selected_gorivo_id':selected_gorivo_id, > 'results': results > }) > > > There must be a better way of doing this, right? I'm a terrible newbie > both at Python and Django --and I'm not a kid anymore, so no more time > to spare hitting my head on walls :-) > > Insights? Ideas? > > Thanks a million, > > -- > Carlos Yoder > http://carlitosyoder.blogspot.com > > > > --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Goog
Re: Checking whether a Foreignkey object has been assigned to anything
Also, I think you need to add null=True to the ForeignKey, like this: category = models.ForeignKey(Category,null=True, blank=True) blank=True indicates the admin interface that a value can be omitted, but null=True is necessary to indicate to the database that the column can be NULL. On 7/12/06, Phil Powell <[EMAIL PROTECTED]> wrote: > > Hi - I've got a bit of a conundrum. > > I have two models, Category and Photo which look something like this: > > class Category(models.Model): > title = models.CharField(maxlength=80) > slug = models.SlugField(prepopulate_from=("title",)) > > class Photo(models.Model): > catalogue_number = models.IntegerField(maxlength=80) > slug = models.SlugField(prepopulate_from=("catalogue_number",)) > category = models.ForeignKey(Category,blank=True) > > There is a one-to-many relationship defined so that a Photo can be > assigned a Category. > > Now, what I want to be able to do is get a list of Categories, but > ONLY those Categories which have been assigned to one or more Photos. > > I can think of plenty of ugly ways to work around this, but wondered > whether anyone had a graceful solution? > > -Phil > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Checking whether a Foreignkey object has been assigned to anything
Hi, If there are not a lot of categories (i.e. a thousand or more), you could iterate over all categories and filter only those that have a photo_set of 1 or more. For example in a view you could do: categories = [c for c in Category.objects.all() if c.photo_set.count()] You could say that it is not very optimal because you are fetching all the categories. But I personally wouldn't worry about it if there are not many categories. Cheers, Jorge On 7/12/06, Phil Powell <[EMAIL PROTECTED]> wrote: > > Hi - I've got a bit of a conundrum. > > I have two models, Category and Photo which look something like this: > > class Category(models.Model): > title = models.CharField(maxlength=80) > slug = models.SlugField(prepopulate_from=("title",)) > > class Photo(models.Model): > catalogue_number = models.IntegerField(maxlength=80) > slug = models.SlugField(prepopulate_from=("catalogue_number",)) > category = models.ForeignKey(Category,blank=True) > > There is a one-to-many relationship defined so that a Photo can be > assigned a Category. > > Now, what I want to be able to do is get a list of Categories, but > ONLY those Categories which have been assigned to one or more Photos. > > I can think of plenty of ugly ways to work around this, but wondered > whether anyone had a graceful solution? > > -Phil > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Having trouble with views
Hi again, > a ForeignKey to Category in your Project model, i.e. that a Project > belongs to a Category, like this: Ooopss, I left something out there. But any case I wanted to apologize for rushing with my previous email, I did not read the email that Malcolm sent before and he is raising very important points. Please take a close look at what he is saying and asking there. You'll need to figure out that first. Cheers, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Having trouble with views
Hi Tomas, I have not read the previous emails, so please excuse me if I'm misinterpreting something. I'll comment on what you said on the last email only. > I have tried with but > I think I need to write a new function inside views.py in my > "portfolio" app, that will bring out that category slug, because it's > not rendring out the category slug now. That is because you are not passing any 'category' variable to the template, but you don't need to. What you need to do is something like this: You access the category of the current project with 'project.category'. I am assuming here that in your models you defined a ForeignKey to Category in your Project model, i.e. that a Project belongs to a Category, like this: > My portfolio urls looks like this now (with corrected typos) > > # Portfolio: > (r'^portfolio/$', 'myproject.portfolio.views.index'), > (r'^portfolio/(?P\d+)/$', > 'myproject.portfolio.views.list'), > (r'^portfolio/(?P\d+)/(?P\d+)/$', > 'myproject.portfolio.views.detail'), The urls you see there are nothing more than regular expressions. In a regular expression you can match a single digit with the expression 'd', and you can match one or more digits by putting the plus sign after the 'd' ( ej. 'd+'). But in your case you need to match words, not digits. To match a word you need to match one or more alphanumeric characters. The expression for an alphanumeric character is 'w', to match one or more you put the plus sign after it: w+. Your urls could look like this: (r'^portfolio/(?P\w+)/$', 'myproject.portfolio.views.list'), (r'^portfolio/(?P\w+)/(?P\w+)/$', 'myproject.portfolio.views.detail'), With the above urls you can match urls like /portfolio/web/school/, where web is the category and school is the slug of the project. But there's a problem. If your category or project slug contains two or more words, those words will be separated by a - (hyphen) character. For example, the url /portfolio/web/school-portal/ will not be matched by the above urls. You need to include the hyphen sign in your regular expression. To do that you need to enclose the 'w' and the '-' in brackets and put the plus sign after the closing bracket like this: (r'^portfolio/(?P\[-w]+)/$', 'myproject.portfolio.views.list'), (r'^portfolio/(?P\[-w]+)/(?P\[-w]+)/$', 'myproject.portfolio.views.detail'), The above urls will now correctly match a path like /portfolio/web/site-portal/ > # Create your views here. > def index(request): > latest_project_list = Project.objects.all().order_by('-created') > return render_to_response('portfolio/index.html', > {'latest_project_list': latest_project_list}) > > def list(request, category_slug): > category_slug_list = Category.objects.all() > return render_to_response('portfolio/index.html', > {'category_slug_list': category_slug_list}) > I see that you are using the same template (index.html) in both views. Is that what you intended? Also, the list() view is supposed to list the projects under the specified Category. I'm guessing that what you want is to get the Category that correspond to the specified category_slug and then list the projects that belong to that category. In that case I would change your list() view like this: def list(request, category_slug): # Get the category and the projects that belong # to this category. category = Category.objects.get(slug=category_slug) projects = category.project_set.all() return render_to_response('portfolio/category_projects.html', {'category':category, 'projects': projects} ) And the portfolio/category_projects.html would look like this: {{ category }} Projects in this category: {% for pro in projects %} {{ pro.title }} {% endfor %} As for the index.html, > > Projects > > {% if latest_project_list %} > > {% for project in latest_project_list %} > {{ > project.title }} > {% endfor %} Change this: with this: I hope this makes things clearer. Cheers! Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: FileBrowser Test Version
Wow, thank you this is fantastic. It's highly probable that I'll use this soon. When I do, I'll make sure to give you feedback and contribute back with something of course. Thank you for releasing this, it will be very useful for a project we will work on soon. Cheers, Jorge On 7/8/06, patrickk <[EMAIL PROTECTED]> wrote: > > today we´ve finished the test version of our django filebrowser. > > some screenshots are here: > http://www.vonautomatisch.at/django/filebrowser/ > > you can download the filebrowser here: > http://www.vonautomatisch.at/django/filebrowser/FileBrowser.zip > > installation shouldn´t take more than 5-10 minutes. > requirements: we are using PIL to create the thumbnails. > > this version is for testing (although we´re already using it). I hope > that some of you will find the time to install the filebrowser. > feedback is more than welcome. > > thanks, > patrick > > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Where to put custom sql?
Hi, I'm not sure if this could help you, or maybe I'm not getting it right. In any case please excuse me if this is something that you already have checked out. You can override the default managers to do different things. I think this could be useful: http://www.djangoproject.com/documentation/model_api/#managers Regards, Jorge On 7/6/06, Filipe <[EMAIL PROTECTED]> wrote: > > hello there, > > I'm starting with Django a new project where I most probably will be > using only custom sql. The most part of the system will be some > (complex) searching for data in a database, so I think I won't take a > lot of benefit from using the ORM. > > What I'm planning is not to have model classes inherited from > django.db.models, but I might still need some model classes to deliver > the collected data to the views and to enclose some business logic. > > The problem is, if I'm not to use django's object-relational mapper, I > will need to write my own data retrieval logic, where is the best place > to put it? perhaps in the models? > > The most part of the data being collected will arrive from the DB in a > somewhat "unnormalized" way, and I'll want to "normalize" it into > several different domain objects. So, placing the data retrieval logic > on the domain objects doesn't really make that much sense to me, > because in each data retrieval operation several types of domain > objects will be retrieved. This is actually logic that has to do with a > bunch of different object types, and not only with a specific object > type. > > Some time ago I've read something about Manipulators and, at the time, > it seemed to be what I am looking for. Is it? > > > Cheers, > Filipe > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: prepare method in Manipulator (and FomField) doesn't get called (and also a minor bug in CheckboxSelectMultipleField)
> > Thanks. I don't know what to put inside html2python. The prepare > method actually sets the list to the values (the first value in the > tuple for choices). I don't think there's anything to change in html2python. As you said the prepare only puts the selected check boxes in the self.data list. Only those check boxes that were selected will be POSTed with the value='on'. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: prepare method in Manipulator (and FomField) doesn't get called (and also a minor bug in CheckboxSelectMultipleField)
Hi Le Roux, > the field name is category_ids, but the checkboxes are named > category_ids1 and category_ids3. That is to be expected. Imagine you have two CheckboxSelectMultipleFields in your manipulator, one named 'color_selection' and other named 'music_selection', which represent foreign keys to Color and Music models. Of course there would be a Color with id 1 and a Music with also an id of 1. That's why the check boxes need to be uniquely identified by prepending the model name: ... etc Otherwise the names would clash. That's why there is the prepare() method, to bring back the selected values. By calling prepare() on get_validation_errors() as you have shown in your patch should make this transparent :) > > to know what the original type of the field was. (I had to make sure > value and text were both strings in my manipulator's __init__ method I guess this is how it is supposed to work, the value must be a string. You can only output strings in html, there's not distinction between a string and a int or something else, everything is a string in html. The values for tags (of any kind) should be strings. The __init__ method for the SelectField and RadioSelectField could be changed to apply str() on each of the values of the passed in choices tuples. But maybe that could be a little 'magical'. > -output.append(' class="v%s" name="%s"%s /> %s' % \ > +output.append(' class="v%s" name="%s"%s value="on" /> %s' > % \ That's a good catch, I have been using check boxes and didn't noticed that they didn't have a value='on'. I guess firefox is supplying the value 'on' by default, or maybe it is being set somewhere in the Django machinery but I don't see where. But yeah, value="on" should be there on the output. Cheers! Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Try to tweak given manipulators or start from scratch?
Hi Todd, > > and for a ForeignKey: > > related_object = OtherObject.objects.get(pk=23) > > new_data['related_object'] = str(related_object.id) > > This, not so much. The related object entry is in the data field of > the FormWrapper when I look at it, but if I render the SelectField it > corresponds to, the empty entry is pre-selected, not the entry that > corresponds to the related_object. Is it not possible to pre-select > something in a SelectField, or do you have to do it some other way? I'm sorry, I forgot to mention that there is something odd with the current default manipulators with regards to foreign keys. As far as I know, this is going to be changed before Django hits 1.0. Let me try to explain this with an example. Suppose you have a Customer model with two fields, a name and a country of origin: class Customer(models.Model): name = models.CharField(maxlength=100) country = models.ForeignKey(Country) The odd thing is that the FormWrapper, when rendering the select field, will pre-select the country according to the value in new_data['country_id'] instead of new_data['country']. But when the form is POSTed to the view, the selected value will come in new_data['country']. In other words, look at this view: def add_customer(request): manipulator = Customer.AddManipulator() new_data = {} errors = {} if request.POST: new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) # The country selected by the user comes in the field # new_data['country'], but if there were errors from # get_validation_errors(), the selection will be lost # because FormWrapper expects 'country_id', # so we need to do this: new_data['country_id'] = new_data['country'] if not errors: manipulator.do_html2python(new_data) manipulator.save(new_data) return HttpResponseRedirect('/some/url/') else: # No POST, set up default values # FormWrapper expects country_id! mexico = Country.objects.get(name='Mexico') new_data['country_id'] = str( mexico.id ) form = forms.FormWrapper(manipulator, new_data, errors) return render_to_response('template.html', {'form': form}) As you can see, the problem is that the FormWrapper uses the value in 'country_id' when rendering the select field in the template, but when the form is posted the value will be available in new_data['country'] (as expected). This does not happen when you build a custom manipulator, I don't know why. Hopefully this discrepancy will disappear before Django hits version 1.0. > Also, since I don't really want the user to be able to change this, > it would be just as nice for me to replace the SelectField that the > AddManipulator creates with a HiddenField of my own, but I can't see This is not recommended at all. It is easy for a malicious user to change the value in a hidden field, thus bypassing your rules and compromising your application. Never put in a hidden field a value that must not be altered, just set the value in your view function. Regards, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Try to tweak given manipulators or start from scratch?
Hi, The choice between doing a custom manipulator from scratch or using the automatically generated one depends on many factors. In an application that I am writing I used a custom manipulator because I needed to create several different objects (from different models) in one single step. So instead of mixing several manipulators and FormWrappers, I created a single custom manipulator and that made things a lot easier. But in other parts of this same application, where I only needed to add or change a single model, I used the default manipulators. On 7/3/06, Todd O'Bryan <[EMAIL PROTECTED]> wrote: > MultipleSelectField to only certain items. Another one needs to be > set to a particular item and the user not given a choice to change it. If you want to use the default manipulator but you do not want the user to be able to change all the fields you can do something like this: def add_object_view(request): manipulator = MyModel.AddManipulator() new_data = {} errors = {} if request.POST: new_data = request.POST.copy() # The user cannot supply the following value so it's hard coded here. new_data['special_value'] = 'The user didn't entered this!' errors = manipulator.get_validation_errors(new_data) if not errors: manipulator.do_html2python(new_data) new_obj = manipulator.save(new_data) return HttpResponseRedirect('/some/url/view/here/') else: # No post, fill up default values new_data['some_field'] = 'default value' form = form.FormWrapper(manipulator, new_data, errors) return render_to_response('some_template.html', {'form': form}) Note that you need to insert the hard coded (or computed) values before the call to get_validation_errors() because otherwise you would get an error about them being required (if they are). Also note that all the fields in new_data MUST be strings before calling get_validation_errors(). So that if you want to insert the current time in a date field you would need to do something like this: new_data['date'] = datetime.now().strftime('%Y-%m-%d') and for a ForeignKey: related_object = OtherObject.objects.get(pk=23) new_data['related_object'] = str(related_object.id) If you want to use an automatic manipulator but want to only restrict the selections in a select list you could subclass the manipulator like this: class MyCustomManipulator(MyModel.AddManipulator): def __init__(self): MyModel.AddManipulator.__init__(self) for field in self.fields: if field.field_name == 'related_object': choices = [(obj.id, obj) for obj in RelatedObject.objects.filter(somecriteria)] field.choices = choices Cheers, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Limiting Choices in AddManipulator
Hi, Maybe you could try this: user_choices = [(u.id, u) for u in User.objects.filter(query)] form['field_name'].formfield.choices = user_choices choices expects a list of tuples in the form of (value, display), so that it generates a select field like this: display1 display2 . etc Regards, Jorge On 7/1/06, Todd O'Bryan <[EMAIL PROTECTED]> wrote: > > How can I limit the choices in an AddManipulator? > > I have a m2m relation to User, and it presents all users. I'd like to > filter and only present a subset. > > I've tried setting the choices of the SelectMultipleField, but haven't > had any luck finding the correct incantation. I've gotten as far as > trying this after I create the form > > form['field_name'].formfield.choices = User.objects.filter(query) > > but get some error regarding unpacking a tuple. (I think this is more a > Python gotcha than a Django one.) > > Any help? > Todd > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: custom form view not keeping information
Hi, Why don't you post some code to see if we can understand better your problem and what modifications could be done? On 6/19/06, hotani <[EMAIL PROTECTED]> wrote: > > I'm pretty much giving up on this -- unless i find an alternative, I'm > going to end up using hidden fields with the generic update view. I > know this is far from ideal, but I can't get anything else to work. > > Basically this is a bug tracker - kind of a get-my-feet-wet app to test > out Django. In order to close a bug, i have to actually show a checkbox > for the boolean field "closed" and the user has to click it to confirm > they are closing the bug. That is not at all what I wanted, but it is > the only thing that works. > > In addition, since I can't seem to write a view that works, I'm having > to pass the "closed_date" and "posted_by (user)" with hidden fields - > this sucks pretty hard, but I'm out of options. > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: The only click to add any class
> And when I save form, got this error: > Invalid value: 'region' should be a 'serp2.apps.common.models.Region'> instance, not a Request The hint is in the error message. You must pass a Region object to the region parameter, new_data['region'] contains only the id that the user selected from the select list. You can do this: def save(self, new_data): t = Town( region = Region.objects.get(pk=new_data['region']), [...] ) --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Initial data for sites framework?
Hi, This is not exactly what you are asking for, but you can modify your own local copy of Django. The file to modify is: trunk/django/contrib/sites/management.py Change the line that looks like this: s = Site(domain="example.com", name="example.com") Cheers, Jorge On 6/4/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > HI. > > I don't use the sites framework. Still, it looks as is I need to > install and initialize it in order to get the feeds (syndication) > framework. > > Is there some place I can put the initial values for the sites > framework, so the standard site is created automatically in the > database and I don't need to log into the admin and edit my site each > time I generate the database again during development)? It always > defaults to "example.com" after a syncdb. > > Daniel > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Ajax support, there is no need for reinventing the wheel
Jeff Forcier <[EMAIL PROTECTED]> wrote: > > As for the general AJAX discussion, I agree wholeheartedly with > James--there's no need to tightly couple a given framework, especially > since good AJAX is exactly what he suggested and what I, at least, have > used successfully--the JS framework on one side and RESTful Django > views that return JSON or XML data on the other side. > I totally agree. I certainly would not like to see more complexity added by bundling an X or Y Ajax library. Better let the developer choose whatever js library he wants. I've been using MochiKit for the client side and SimpleJSON at the server side which is extremely easy to use. And adding a '/myobject/(\d+)/json/' url and view is dead simple. So far I don't see any need to "Add AJAX support to Django", what support? As for the bundled admin application, it is a "contributed" application which could use any ajax library without, it shouldn't introduce any complexity to "Django as a framework". Cheers, Jorge --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: How to validate CheckboxField?
Hi, Yeah it's strange that the CheckboxField doesn't have a validator list. I guess this is worth a ticket. But there's a way to get what you want without passing a validator list. If you define a method "validate_field_name", that method will be called when you call the get_validation_errors() on the manipulator. You can use something like this: from django.core import validators from django import forms class TestManipulator(forms.Manipulator): def __init__(self): self.fields = ( forms.CheckboxField(field_name='first'), forms.CheckboxField(field_name='second'), ) def validate_first(self, data, all_data): # If this is not selected and the other checkbox isn't # selected either, raise an error. if not data and not all_data['second']: raise validators.ValidationError, "one of these checkboxes is required" validate_first.always_test = True validate_first() will be called and if both checkboxes are unchecked it will raise an error. Because the field is not marked as required, you must set an "always_test" attribute, otherwise the validatior wouldn't be called if the field was empty. You could also add a validate_second() method, but in this case is not necessary since you only want to check if any of the two fields is checked. Regards, Jorge On 5/26/06, Jaroslaw Zabiello <[EMAIL PROTECTED]> wrote: > > I am using Django SVN. How to validate tthe form which consists of two > CheckboxField fields. The rule is: the form is validated if ANY of > those fields is checked. My manipulator is: > > from django import forms > class TestManipulator(forms.Manipulator): > def __init__(self): > self.fields = ( > forms.CheckboxField(field_name='first'), > forms.CheckboxField(field_name='second'), > ) > > The problem is, I have no access to validators parameter: > forms.CheckboxField(field_name='first', validators=[myvalidator]) > because (as I found in django/forms/__init__.py file) the constructor > has only 'field_name' and 'checked_by_default'. > > I know that I can use CheckboxSelectMultipleField, e.g. > > forms.CheckboxSelectMultipleField( > field_name='options', > choices=[('1', '2'), ('first', 'second')], > validator_list=[validators.isNotEmpty]), > ) > > but generated html code is not acceptable for me, because I do not want > to have ... list. > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Foreign keys in views
Hi, I also found that behavior and what I did was to copy new_data['station'] to new_data['station_id'] when there were errors from "get_validation_errors()". Like this: def change_recording(request, recording_id): snip. if request.POST: new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: manipulator.do_html2python(new_data) new_recording = manipulator.save(new_data) return HttpResponseRedirect("/dwasrod/") else: new_data['station_id'] = new_data['station'] new_data['other_foreign_id'] = new_data['other_foreign'] else: new_data = recording.__dict__ snip I later had to create a custom manipulator instead of using the default one. With a custom manipulator you don't have this field name discrepancy, and don't need to do that value copying. I now prefer to use a custom manipulator. Cheers, Jorge On 5/25/06, Christian Schneider <[EMAIL PROTECTED]> wrote: > Hi all, > > I've written (well copied) the following view. In my model I have a defined > an attribute "station = models.ForeignKey(Station)". Now, if I call the > change view, the station is selected. However, if I submit the change view > with some errors, the station is de-selected in the new view. > > I've also written a create view that is given a station id on creation an > pre-populates the interface. Here I found that the foreign key's id comes in > as new_data["station"] but has to go out as new_data["station_id"]. Is that > correct and do the generic views stuff like that under the hood? > > Form fields for many-to-many relations work as expected, so maybe I'm doing > something wrong with the foreign key fields. > > Any hints are - as always - welcome > > chris > > > def change_recording(request, recording_id): > try: > manipulator = Recording.ChangeManipulator(recording_id) > except: > raise Http404 > > recording = manipulator.original_object > > errors = {} > new_data = {} > > if request.POST: > new_data = request.POST.copy() > errors = > manipulator.get_validation_errors(new_data) > if not errors: > manipulator.do_html2python(new_data) > new_recording = manipulator.save(new_data) > return HttpResponseRedirect("/dwasrod/") > else: > new_data = recording.__dict__ > > form = FormWrapper(manipulator, new_data, errors) > return > render_to_response('aufnahmen/recording_form.html', > {'form': form}) > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Forms: SelectField with default value
I'm not sure if you can specify a default to use with the built-in Admin views. However, if you are developing your own views you can set the default data to pass to the FormWrapper with something like this (I'm using this code and it works): def mycustomview(request): manipulator = MyModel.AddManipulator() new_data = {} errors = {} if request.POST: new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) if not errors: manipulator.do_html2python(new_data) new_object = manipulator.save(new_data) return HttpResponseRedirect('/finished/') else: # No POST, fill up default values #Use the id of the related value that you want as default new_data['my_select_field'] = '3' form = forms.FormWrapper(manipulator, new_data, errors) data = { 'form': form, } return render_to_response('my_template.html', data) That should work for you if you are doing a custom view. But if you need this functionality in the Admin, I think it is possible to wrap an Admin view with a custom view of yours. I have not done that, but you could search about it in the mailing list. Regards, Jorge On 5/10/06, Juancho <[EMAIL PROTECTED]> wrote: > > Hello, > > I am trying to get a SelectField to render with a default value, i.e., > a pre-selected choice. > > With the current SelectField implementation, this is not possible. I > see this issue has been addressed before but was closed as "wontfix" > with this reason: > > "This is not in the scope of the formfields.py framework. Formfields > just know how to display themselves -- they don't know (or care) about > data. Put this in your business logic." > > More here ... > http://code.djangoproject.com/ticket/1081 > > Can someone explain to me the expected way to render a select field > with selected value?? The only way i can see currently is to implement > my own custom SelectField which will render HTML with a default value. > > I don't understand how formfields can not "know (or care) about data" > when they are bound to a specific data list in the first place, in > order to even display a list of data to select from. > > Comments/clarification/help?? thx all > juancho > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: No Subclassing in models yet? How would you guys do the following:
He is using a common joke found in the slashdot community. See http://en.wikipedia.org/wiki/Slashdot_culture But then again, this is not slashdot. So yeah, maybe he was drunk. On 5/10/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > Hmm - were you drunk when you posted this? > > > > > --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---
Re: Question
> In my urls.py I use > (r'^shop/(?P.*?)/','shopproject.apps.shop.views.shop.Index') > but also > (r'^TradeOffice/','shopproject.apps.shop.views.shop.TradeOffice'), > > so that I can not change simply > (r'^shop/(?P.*?)/','shopproject.apps.shop.views.shop.Index') > into > (r'^(?P.*?)/','shopproject.apps.shop.views.shop.Index') Why not? The patterns will be checked from top to bottom. So if you put (r'^(?P.*?)/','shopproject.apps.shop.views.shop.Index') as the last pattern it should work. --~--~-~--~~~---~--~~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~--~~~~--~~--~--~---