Customizing form fields display
Can anyone suggest a way to customize model field display? For example if I have a model called Course with fields n_girls and n_students, if for a particular record n_girls = 4 and n_students = 10, I want to display for n_girls: "40% (4)" instead of just "4". Obviously I can do this in the template but there are multiple fields I want to customize and the lack of switch/elsif statement in the templates would make for a deeply nested structure so I'd rather do it upstream in the model. Thanks in advance. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Your IDE of choice
Pydev works pretty well, including visual debugging of the test server + test suite On Jan 6, 1:48 pm, HBwrote: > Hey, > What is your favorite IDE for coding Django projects? > Any ideas about PyDev and ActiveState Komodo IDE? > Thanks. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Extra attributes in model fields
Any suggestion on how to decorate a model with extra attributes? On Jan 1, 9:39 am, sagi s <sag...@yahoo.com> wrote: > I'd like to store extra attributes in the model fields so I can > control the subsequent field-specific behavior from there. > > Let's say I have a model that stores metrics I then need to chart. > > In the view, I prefer not to have some logic that says: > > metrics = Metric.object.all() > create_chart([metric.productivity for metric in metrics], "bar_chart") > create_chart([metric.defects for metric in metrics], "pie_chart") > > I'd rather have something like: > > for metric_type in Metric.fields: > create_chart([metric."metric_type" for metric in metrics], > metric."metric_type".chart_type) > > The big advantage here is that I can add a new metrics element from > the model without changing the view (Open-Close principle...) > > So it would be great if I could do something like: > > class Metric(models.Model): > productivity = PositiveIntegerField( > verbose_name = "the number of hot dogs we have produced during > that period", > chart_type = "bar_chart" > ) > ... > > However the model rejects fields it does not recognize. > > I tried creating my own doctored model to wrap the built-in models: > > class _PositiveIntegerField(models.fields.CharField): > def __init__(self, *args, **kwargs): > if "extra_attrs" in kwargs: > self.extra_attrs = kwargs["extra_attrs"] > del kwargs["extra_attrs"] > models.fields.PositiveIntegerField.__init__(self, *args, > **kwargs) > > This way I can do: > > class Metric(models.Model): > productivity = _PositiveIntegerField( > verbose_name = "the number of hot dogs we have produced during > that period", > extra_attrs = {'chart_type' : "bar_chart"} > ) > ... > > There are two problems here: > 1. I'd need to wrap every field type > 2. In the ModelForm I create from this model the type still registers > as the built-in type: > > class MetricForm(models.ModelForm): > class Meta: > model = Metric > > >>> mf = MetricForm() > >>> mf.fields['productivity'] > > > > Any suggestion as to how to design this right? --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Extra attributes in model fields
I'd like to store extra attributes in the model fields so I can control the subsequent field-specific behavior from there. Let's say I have a model that stores metrics I then need to chart. In the view, I prefer not to have some logic that says: metrics = Metric.object.all() create_chart([metric.productivity for metric in metrics], "bar_chart") create_chart([metric.defects for metric in metrics], "pie_chart") I'd rather have something like: for metric_type in Metric.fields: create_chart([metric."metric_type" for metric in metrics], metric."metric_type".chart_type) The big advantage here is that I can add a new metrics element from the model without changing the view (Open-Close principle...) So it would be great if I could do something like: class Metric(models.Model): productivity = PositiveIntegerField( verbose_name = "the number of hot dogs we have produced during that period", chart_type = "bar_chart" ) ... However the model rejects fields it does not recognize. I tried creating my own doctored model to wrap the built-in models: class _PositiveIntegerField(models.fields.CharField): def __init__(self, *args, **kwargs): if "extra_attrs" in kwargs: self.extra_attrs = kwargs["extra_attrs"] del kwargs["extra_attrs"] models.fields.PositiveIntegerField.__init__(self, *args, **kwargs) This way I can do: class Metric(models.Model): productivity = _PositiveIntegerField( verbose_name = "the number of hot dogs we have produced during that period", extra_attrs = {'chart_type' : "bar_chart"} ) ... There are two problems here: 1. I'd need to wrap every field type 2. In the ModelForm I create from this model the type still registers as the built-in type: class MetricForm(models.ModelForm): class Meta: model = Metric >>> mf = MetricForm() >>> mf.fields['productivity'] Any suggestion as to how to design this right? --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Customizing ModelForm fields appearance
I really like the concept of generating a form from a model using ModelForm but would like to customize the apprearance slightly (e.g. size of the TextInput etc.). Any suggestion as to how to do this? I looked at the forms module code but got lost in the maze of the meta programming... Thanks in advance --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Using the test client to verify form fields content
I'd like to use the test client to verify that when there's an error in a form field, the input field in the response is populated with the original input. So I'd like to do something like: iteration = 'bad data' response = self.client.post('/metrics/add/', { 'iteration' : iteration, ... } ... self.failUnlessEqual(response.context[0]['form'].fields ['iteration'].value), 'bad data') Would be great to know where I can fish this from (the last line in the above snippet is just for illustration of how I would hope to access the value) Django version is 1.0, the form is a ModelForm in case it matters. Cheers --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: ModelForms customization conundrum
A related problem is that I'd like to use the test client to verify that when there's an error in the field the input field in the response is populated with the original input. So I'd like to do something like: iteration = 'bad data' response = self.client.post('/metrics/add/', { 'iteration' : iteration, ... ) self.failUnlessEqual(response.context[0]['form'].fields ['iteration'].value), 'bad data') Would be great to know where I can fish this from (the last line in the above snippet is just for illustration of how I would hope to access the value) Cheers, Sagi On Dec 17, 3:40 pm, sagi s <sag...@yahoo.com> wrote: > On Dec 16, 4:49 pm, "James Bennett" <ubernost...@gmail.com> wrote: > > > On Tue, Dec 16, 2008 at 7:19 AM, sagi s <sag...@yahoo.com> wrote: > > > So I'm looking at the data available in the template to try to get my > > > hands dirty and restore all this manually but can't find how all this > > > magic works. I'm in the debugger looking at the form passed to the > > > template via the context and this looks like a mountain I'd rather not > > > climb (I'll spare you the details of the data structure here). > > > There is no "magic" involved in the form; a ModelForm simply > > introspects the model to get the model class' Field objects and, for > > each field to be included in the form, calls that Field object's > > 'formfield()' method to get a form field. > > I guess "magic" is a relative term. I am looking at the forms module > and as far as I can see it is anything but trivial. > > > > > Of course, the moment you put a custom form field definition in the > > form class, it ignores whatever comes from the model in favor of your > > definition. So, either: > > > 1. Stop overriding the field definition, and instead poke at the > > attributes you want to change inside your form's __init__ method, or > > I can override the __init__ method but I'm back to the problem of > figuring out what to "poke" at. > In the debugger I see this monstruous and deeply-nested data structure > with a bazillion _meta's all over the place. Not sure where I can > plant the attributes. Looking at the code with all that > __meta__programming___ doesn't get me anymore enlightened. > > > 2. Use the same method the ModelForm uses to get the form field, and > > then change the attributes you want to change before using the > > resulting form field object to define your form. > > No joy in this direction either. > > > > > It's really not that difficult once you take a look at the code > > involved; probably no more than a half-dozen lines of code if you're > > just tweaking a couple of fields. > > I'm not a novice with Python so half-dozen lines of codes sounds like > something I can deal with. I just need to know what those lines should > say :) > > Seems like what I'm trying to accomplish should be bread-and-butter > stuff for Django (tweak a bit the appearance of a ModelForm). Would be > good to have an easy way to do it. > > If I ever learn I'm willing to take it upon myself to create a recipe > somewhere. > > Thanks for the help here Jim. If you have more hints I'll appreciate > much. > > > Also, when trying to work out what's happening, a debugger is probably > > the worst possible choice; the underlying code is quite clear and > > readable, and is far superior for getting an understanding of how the > > system works. > > > -- > > "Bureaucrat Conrad, you are technically correct -- the best kind of > > correct." --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: ModelForms customization conundrum
On Dec 16, 4:49 pm, "James Bennett" <ubernost...@gmail.com> wrote: > On Tue, Dec 16, 2008 at 7:19 AM, sagi s <sag...@yahoo.com> wrote: > > So I'm looking at the data available in the template to try to get my > > hands dirty and restore all this manually but can't find how all this > > magic works. I'm in the debugger looking at the form passed to the > > template via the context and this looks like a mountain I'd rather not > > climb (I'll spare you the details of the data structure here). > > There is no "magic" involved in the form; a ModelForm simply > introspects the model to get the model class' Field objects and, for > each field to be included in the form, calls that Field object's > 'formfield()' method to get a form field. I guess "magic" is a relative term. I am looking at the forms module and as far as I can see it is anything but trivial. > > Of course, the moment you put a custom form field definition in the > form class, it ignores whatever comes from the model in favor of your > definition. So, either: > > 1. Stop overriding the field definition, and instead poke at the > attributes you want to change inside your form's __init__ method, or I can override the __init__ method but I'm back to the problem of figuring out what to "poke" at. In the debugger I see this monstruous and deeply-nested data structure with a bazillion _meta's all over the place. Not sure where I can plant the attributes. Looking at the code with all that __meta__programming___ doesn't get me anymore enlightened. > 2. Use the same method the ModelForm uses to get the form field, and > then change the attributes you want to change before using the > resulting form field object to define your form. No joy in this direction either. > > It's really not that difficult once you take a look at the code > involved; probably no more than a half-dozen lines of code if you're > just tweaking a couple of fields. > I'm not a novice with Python so half-dozen lines of codes sounds like something I can deal with. I just need to know what those lines should say :) Seems like what I'm trying to accomplish should be bread-and-butter stuff for Django (tweak a bit the appearance of a ModelForm). Would be good to have an easy way to do it. If I ever learn I'm willing to take it upon myself to create a recipe somewhere. Thanks for the help here Jim. If you have more hints I'll appreciate much. > Also, when trying to work out what's happening, a debugger is probably > the worst possible choice; the underlying code is quite clear and > readable, and is far superior for getting an understanding of how the > system works. > > -- > "Bureaucrat Conrad, you are technically correct -- the best kind of correct." --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
ModelForms customization conundrum
Maybe I'm missing something here but I've been struggling with some basic forms customization issues. I'm using ver. 1.0 I have created a simple model (Metric) and a form to go with it, deriving from django.forms.ModelForm with the model set it the Meta as per the examples. Out-of-the-box the form is ugly (understandably so) so I need to control its appearance, e.g. hook a calendar widget to a date field, control the size of input fields etc. This can be done by overriding fields, e.g.: class MetricForm(ModelForm): # Override some fields to customize the appearance iter = forms.CharField(widget=forms.TextInput(attrs={'size':'3'})) end_date = forms.CharField(widget=forms.TextInput(attrs= {'class':'date-pick', 'size':'10'})) class Meta: model = Metric Now the thing is that for fields I override, I lose the help_text I have set in the model, I lose the value entered in an input being echoed back to the user when validation fails, I lose the verbose_name... So I'm looking at the data available in the template to try to get my hands dirty and restore all this manually but can't find how all this magic works. I'm in the debugger looking at the form passed to the template via the context and this looks like a mountain I'd rather not climb (I'll spare you the details of the data structure here). Suggestion appreciated. --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
ifequal template tag quirks
I tried to compare user ids in a template almost exactly like the example in the docs: {% ifequal user_id copy.checkout.user.id %} however, it seems like user_id (a context variable I'm passing) is a string and the other id that comes from the model is a long so the comparison always fails. I would use the stringformat filter to convert but this works only for simple variable statements. One way around this is to change the django library code to convert the variables to strings before while comparing: in 0.96, template/defaulttags.py: IfEqualNode(Node): if (self.negate and str(val1) != str(val2)) or (not self.negate and str(val1) == str(val2)): What can we lose by this? Any suggestion on how to do this without this hack? --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
newforms.form_for_model() does not map CharField with choices into SELECT
I am generating a form for a model that contains a CharField with choices. According to the documentation I expect to see this translated into a SELECT form field but all I get is a simple TEXT form field: models.py: class Publication(models.Model): PUBLICATION_TYPES = ( ('B', 'Book'), ('P', 'Periodical'), ('D', 'DVD'), ('C', 'CD'), ('O', 'Other'), ) type = models.CharField(maxlength=1, choices=PUBLICATION_TYPES) ... >>> from django import newforms as forms >>> pubform = forms.form_for_model(Publication) >>> pf = pubform() >>> pf.as_table() u'Type:\n... Any idea? --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Django database API - What is it good for?
I've been playing around with Django for a couple of weeks. I'm finding myself spending most of my type tinkering with the Database API to try to wrestle the information I need out of my database. At this point it looks to me like I have replaced one set of incantations (SQL) for another (Database API's query languages). I must be missing the point coz I'm starting the miss SQL... For example I want to get all the Users belonging to the "Staff" Group (User and Group are Django models so it's not like I'm laying out my models poorly). Is it: >>> users = User.objects.filter(groups__contains="Staff") ? Surely not. It is... darn - Can I just use SQL and be done with it? Sorry if I'm iconoclasting stuff here. --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
newforms - form for multiple models
I am trying to create a form for a couple of models: PubForm = forms.form_for_model(Publication) CopyForm = forms.form_for_model(Copy) class PubCopyForm(PubForm, CopyForm): pass I would expect to see a combination of the Copy and Publication fields in the form but I only see Publication's fields. Any suggestions on how to achieve 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?hl=en -~--~~~~--~~--~--~---
Rails-like Flash in Django
In Rails, flash is a way to display a message in the next page. It is extremely useful to provide lightweight feedback to user operations. For examples when the user, say, submits a new article and after clicking on the "Submit" button, then is redirected to the front page, you want to let him know that his submission was successful on the front page. What you would like to do is something like this: ...views.py def new_article(request): ... article.save() flash("Your article was saved") ... HttpRedirect("frontpage") I have implemented as a context processor: Step 1: create a file called session_context_processor.py: def flash(request): # Add the flash message from the session and clear it flash = "" if 'flash' in request.session: flash = request.session['flash'] del request.session['flash'] return {'flash': flash} Step 2: Add the context processor to settings.py: TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', ... 'session_context_processor.flash', ) Step 3: Add the context to *every* view that renders a template: e.g. change: return render_to_response('mytemplate.html', context) to: return render_to_response('mytemplate.html', context, context_instance=RequestContext(request)) Again: do this in every view which should be displaying a flash (I have it in all views) Step 4: Add the flash message to your base template: ... ... {{ flash }} ... Step 5: Set the flash whenever desired. Following the example above: ...views.py def new_article(request): ... article.save() request.session['flash'] = "Your article was saved" ... HttpRedirect("frontpage") That's it. I've seen other pointers on how to do it but this one makes sense to me. One thing I want to add is a flash type to help the template format the flash differently depending on whether it represents an error, successful operation etc. Suggestions for improvement are welcome. --~--~-~--~~~---~--~~ 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: Including view in a template
Not clear on what you mean by "more robust views". Can you please elaborate? Regarding the term "views", I do mean actually invoking the python function via the url routing system. I would settle for calling a regular python function that returns some html snippet but I think the existing views would just work fine. Regarding custom template tags, I guess I expect many users to want to use django this way, so I think that having a "load_view" template element would be useful. Don't you agree? Cheers, Sagi On Aug 1, 10:29 pm, "James Bennett" <[EMAIL PROTECTED]> wrote: > On 8/1/07, sagi s <[EMAIL PROTECTED]> wrote: > > > I realize that this is an option but it seems to me more natural to > > control the content from the template so a designer can build views > > using "lego-blocks", without having to tweak the view. > > You either want: > > 1. More robust views, or > 2. Some custom template tags which allow your template authors to > access the things they want to pull in. > > Using the term "views" here to refer to both "the Python function to > which the URL is routed" and "some piece of content I want in a > template" is also likely to end up in severe confusion... > > -- > "Bureaucrat Conrad, you are technically correct -- the best kind of correct." --~--~-~--~~~---~--~~ 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: Including view in a template
Thanks for the quick reply! I realize that this is an option but it seems to me more natural to control the content from the template so a designer can build views using "lego-blocks", without having to tweak the view. Cheers, Sagi On Aug 1, 10:01 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > In the view.py code that you have calling your > frontpage_template.html, you should put your code to query the > database and generate your user list and articles. You would then > pass these to your html template via: > > return render_to_response('frontpage_template.html', > {'list_users':list_users,'latest_articles':latest_articles}) > > On Aug 1, 2:34 pm, sagi s <[EMAIL PROTECTED]> wrote: > > > I am trying to find a way to include a view in a template. The view > > generates an html snippet based on a DB query + another template. In > > pseudocode what I am trying to achieve is: > > > frontpage_template.html: > > {{% include header.html %}} > > {{% load /views/list_users %}} > > {{% load /views/latest_articles %}} > > ... > > > I tried loading a template instead and have that template issue an > > Ajax Updater request to a view upon loading but it seems like an > > overkill. > > > Any suggestions? --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Including view in a template
I am trying to find a way to include a view in a template. The view generates an html snippet based on a DB query + another template. In pseudocode what I am trying to achieve is: frontpage_template.html: {{% include header.html %}} {{% load /views/list_users %}} {{% load /views/latest_articles %}} ... I tried loading a template instead and have that template issue an Ajax Updater request to a view upon loading but it seems like an overkill. Any suggestions? --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---
Null=True not respected by admin?
I created a table where some of the fields have null=True since it's okay for them to be empty. Looking at the schema in mysql this option was correctly translated into the DB's schema, however when I try to add an entry via the admin interface I get errors on those fields saying that 'This field is required'. Any ideas? --~--~-~--~~~---~--~~ 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 -~--~~~~--~~--~--~---