how to set up a calculated field in Django?
Hi, i have the following items in my model: mother_alive = models.IntegerField(choices=YES_NO_CHOICES, blank=True, null=True, default=1) father_alive = models.IntegerField(choices=YES_NO_CHOICES, blank=True, null=True, default=1) and I'd like to set up a generated field for them so I'd be able to detect whether the child is an orphan or not. In MySQL i believe it'd look like this: orphan varchar(101) GENERATED ALWAYS AS (mother_alive+father_alive) VIRTUAL, I don't know how to change my model to do that... Any help? -Eileen -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/32b1c56f-f52d-4b63-bd93-db25cc1e89a6%40googlegroups.com.
Changed SelectDateWidget to SelectMonthDayWidget; tried to run it in command line.
Hi, I'm a newbie and I want to change the Django SelectDateWidget to SelectMonthDayWidget because I can't use the year in my application. I had been getting another error (which I don't recall right now) on the statement that started 'html['month']' so, I decided to convert it to command line to get a better picture of what's going on. Unfotunately, now I get: Traceback (most recent call last): File "SelectMDWidget.py", line 34, in class SelectMonthDayWidget(month,day_ok): TypeError: Error when calling the metaclass bases unicode() argument 2 must be string, not tuple What am I doing wrong? I'm passing the class two strings... """ HTML Widget classes """ from __future__ import unicode_literals import copy import re from itertools import chain from django.conf import settings from django.forms.widgets import Widget, Select from django.templatetags.static import static from django.utils import formats from django.utils.dates import MONTHS from django.utils.formats import get_format from django.utils.safestring import mark_safe from django.utils.six.moves import range from django.utils.translation import ugettext_lazy, gettext_lazy as _ from django.utils.deprecation import ( RemovedInDjango20Warning, RenameMethodsBase, ) from django.utils.encoding import ( force_str, force_text, python_2_unicode_compatible, ) __all__ = ('SelectMonthDayWidget', ) day_ok = u'' month = u'' class SelectMonthDayWidget(month,day_ok): """ A Widget that splits date input into three boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = (0, '---') month_field = month #'%s_month' day_field = day_ok #'%s_day' select_widget = Select def __init__(self, attrs=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError('empty_label list/tuple must have 2 elements.') self.month_none_value = (0, empty_label[0]) self.day_none_value = (0, empty_label[1]) else: if empty_label is not None: self.none_value = (0, empty_label) self.month_none_value = self.none_value self.day_none_value = self.none_value @staticmethod def _parse_date_fmt(): fmt = get_format('DATE_FORMAT') escaped = False for char in fmt: if escaped: escaped = False elif char == '\\': escaped = True elif char in 'bEFMmNn': yield 'month' elif char in 'dj': yield 'day' def render(self, name, value, attrs=None): try: month_val, day_val = value.month, value.day except AttributeError: month_val = day_val = None if isinstance(value, six.string_types): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] v = datetime.datetime.strptime(force_str(value), input_format) month_val, day_val = v.month, v.day except ValueError: pass if year_val is None: match = self.date_re.match(value) if match: month_val, day_val = [int(val) for val in match.groups()] html = {} choices = list(self.months.items()) html['month'] = self.create_select(name, self.month_field, value, month_val, choices, self.month_none_value) choices = [(i, i) for i in range(1, 32)] html['day'] = self.create_select(name, self.day_field, value, day_val, choices, self.day_none_value) output = [] for field in self._parse_date_fmt(): output.append(html[field]) return mark_safe('\n'.join(output)) def id_for_label(self, id_): for first_select in self._parse_date_fmt(): print ('1','%s_%s' % (id_, first_select)) return '%s_%s' % (id_, first_select) else: print ('2','%s_month' % id_) return '%s_month' % id_ def value_from_datadict(self, data, files, name): m = data.get(self.month_field % name) d = data.get(self.day_field % name) if m == d == "0": return None if m and d: if settings.USE_L10N: input_format = get_format('DATE_INPUT_FORMATS')[0] try: date_value = datetime.date(int(y), int(m), int(d))
need to find out if someone is an orphan when I have mother_alive and father_alive fields in the database
Hi, I need to find out if someone is an orphan when I have mother_alive and father_alive fields in the database. Stepfathers, and stepmothers etc aren't counted when determining if someone is an orphan, only their birth mother, and birth father. I tried if form['orphaned'].data == True: q = context['child_filter'].filter(Q(request.POST.get('mother_alive') == 0 and request.POST.get('father_alive') == 0)) but I got an error on it. does anyone know what I did wrong? -Eileen -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f49ad522-cbcc-4aa9-8126-636231b36bfd%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: how do I handle a dropdown in Django whose only purpose is to get data.
well, you certainly got me correct! I'm fairly new to python - didn't do much coding to learn. Trial by fire, sort of. and the original person who put this together is now gone from the company and won't answer any outstanding questions. Plus, I *think* he got most of the code from 3rd party sources. I could be wrong on that. I was raised on Perl and PL/I (as ancient as the latter may seem) On Friday, January 26, 2018 at 3:12:19 PM UTC-5, Melvyn Sopacua wrote: > > There are a bunch of issues with this code: > > 1) Spell Physical correctly: > > > > 2 - Phyiscal > > > if form.data['handicapped'] is 'Physical' or 'Mental': > > > handicapped = forms.ChoiceField(choices=[(x, x) for x in ('---', > > 'Mental', 'Physcal')], required=False) > > Comparison of non boolean or None values using "is" instead of "==": > > if form.data['handicapped'] is 'Physical' or 'Mental': > > Use of or as if natural language in RHS of comparisons (should be a == x > or a > == y, not a == x or y): > > > if form.data['handicapped'] is 'Physical' or 'Mental': > > if form['handicapped'].data == 1 or 2: > > So this reads as if someone with very little knowledge of Python is > modifying > a 3rd party app, written by someone with a decent amount of Django > experience. > > Finally, when accessing form data from a valid form, we access > form.cleaned_data and generally use a local variable to reference the > dict: > > if form.is_valid(): > data = form.cleaned_data > # do stuff with data > -- > Melvyn Sopacua > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/394ce2de-fc0c-4ed2-9c89-7dab9a1c727a%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: how do I make django search for male or female without needing to specify an age?
I should add that this initally loads a list of children without specifying either gender or age On Friday, January 26, 2018 at 12:05:04 PM UTC-5, eil...@themaii.org wrote: > > I have a file: views.py which refers to two main fields on the page: age > and gender > Right now, the search requires that an age to be chosen whether or not the > gender is, and I'd like to make the age optional as well. I.e get all the > children. > Additionally, I'd like to search for only males or females without > selecting an age... > > -Eileen > from __future__ import unicode_literals > from django.contrib.auth import get_user_model > from django.shortcuts import redirect > from django.template.response import TemplateResponse > from django.http import HttpResponse > from django.db.models import Q > from django.db.models import F > from mezzanine.conf import settings > from sponsorship.forms import FilterForm > from sponsorship.models import Child > from pinax.stripe.models import Customer > import json > import logging > > logger = logging.getLogger(__name__) > > User = get_user_model() > > steps = [{'title': 'Find a child to sponsor', 'no': '1'}, {'title': 'Sign > up or sign in', 'no': '2'}] > > def filterchain_all(request, app_name, model_name, method_name, gender): > gender_dict = {'MALE': 0, 'FEMALE': 1} > if gender in gender_dict: > qs = > Child.objects.filter(gender=gender_dict[gender]).order_by('age') > results = list(qs) > final = [] > for item in results: > if int(item.age) not in [d['display'] for d in final]: > final.append({'value': int(item.age), 'display': > int(item.age)}) > return HttpResponse(json.dumps(final), > content_type='application/json') > else: > return HttpResponse(json.dumps({'success': True}), > content_type='application/json') > > def children_list(request, template="pages/sponsorship.html", > extra_context=None): > templates = [] > templates.append(template) > children = Child.objects.filter(Q(has_photo=1) & > Q(image__isnull=False) & Q(sponsor__isnull=True)) > context = {"child_filter": children, "filter_form": FilterForm(), > "steps": steps, "activestep": "1"} > if request.method == "POST": > if "id" in request.POST: > child_id = > context['child_filter'].filter(id=request.POST['id'])[0].child_id > authenticated = request.user.is_authenticated() > if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not > authenticated: > url = > "/accounts/signup/?next=/donate/product/sponsor-a-child/new_customer/%s" % > child_id > return redirect(url) > else: > url = "/donate/product/sponsor-a-child/%s" % child_id > return redirect(url) > else: > form = FilterForm(request.POST) > gender_dict = {'MALE': 0, 'FEMALE': 1} > > search_message = "There are no children that match your > selection" > if form.is_valid() and form.data['gender'] != '-': > if form.data['gender'] is 0 or 1: > q = > context['child_filter'].filter(Q(gender=gender_dict[request.POST['gender']])) > > import pdb; pdb.set_trace() > if form['handicapped'].data == 1 or 2: > q = > context['child_filter'].filter(Q(handicapped=handicapped_dict[request.POST['handicapped']])) > > if request.POST['age'] != '': > q = > context['child_filter'].filter(Q(age=request.POST['age'])) > > # start of output using search parameters > > if q.count() > 1: > search_message = "There are %s children that match your > selection of %s" % (q.count(), request.POST['gender']) > else: > search_message = "There is 1 child that matches your > selection of %s" % (request.POST['gender']) > > if q.count() > 1: >search_message = ", age: %s" % (request.POST['age']) > else: >search_message = ", age: %s" % (request.POST['age']) > > context['child_filter'] = q > context['filter_form'] = FilterForm() > context['activestep'] = "1" > context['search_message'] = search_message > extra_context = {"message": "Updating filter"} > context.update(extra_context or {}) > return TemplateR
how do I make django search for male or female without needing to specify an age?
I have a file: views.py which refers to two main fields on the page: age and gender Right now, the search requires that an age to be chosen whether or not the gender is, and I'd like to make the age optional as well. I.e get all the children. Additionally, I'd like to search for only males or females without selecting an age... -Eileen from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.shortcuts import redirect from django.template.response import TemplateResponse from django.http import HttpResponse from django.db.models import Q from django.db.models import F from mezzanine.conf import settings from sponsorship.forms import FilterForm from sponsorship.models import Child from pinax.stripe.models import Customer import json import logging logger = logging.getLogger(__name__) User = get_user_model() steps = [{'title': 'Find a child to sponsor', 'no': '1'}, {'title': 'Sign up or sign in', 'no': '2'}] def filterchain_all(request, app_name, model_name, method_name, gender): gender_dict = {'MALE': 0, 'FEMALE': 1} if gender in gender_dict: qs = Child.objects.filter(gender=gender_dict[gender]).order_by('age') results = list(qs) final = [] for item in results: if int(item.age) not in [d['display'] for d in final]: final.append({'value': int(item.age), 'display': int(item.age)}) return HttpResponse(json.dumps(final), content_type='application/json') else: return HttpResponse(json.dumps({'success': True}), content_type='application/json') def children_list(request, template="pages/sponsorship.html", extra_context=None): templates = [] templates.append(template) children = Child.objects.filter(Q(has_photo=1) & Q(image__isnull=False) & Q(sponsor__isnull=True)) context = {"child_filter": children, "filter_form": FilterForm(), "steps": steps, "activestep": "1"} if request.method == "POST": if "id" in request.POST: child_id = context['child_filter'].filter(id=request.POST['id'])[0].child_id authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "/accounts/signup/?next=/donate/product/sponsor-a-child/new_customer/%s" % child_id return redirect(url) else: url = "/donate/product/sponsor-a-child/%s" % child_id return redirect(url) else: form = FilterForm(request.POST) gender_dict = {'MALE': 0, 'FEMALE': 1} search_message = "There are no children that match your selection" if form.is_valid() and form.data['gender'] != '-': if form.data['gender'] is 0 or 1: q = context['child_filter'].filter(Q(gender=gender_dict[request.POST['gender']])) import pdb; pdb.set_trace() if form['handicapped'].data == 1 or 2: q = context['child_filter'].filter(Q(handicapped=handicapped_dict[request.POST['handicapped']])) if request.POST['age'] != '': q = context['child_filter'].filter(Q(age=request.POST['age'])) # start of output using search parameters if q.count() > 1: search_message = "There are %s children that match your selection of %s" % (q.count(), request.POST['gender']) else: search_message = "There is 1 child that matches your selection of %s" % (request.POST['gender']) if q.count() > 1: search_message = ", age: %s" % (request.POST['age']) else: search_message = ", age: %s" % (request.POST['age']) context['child_filter'] = q context['filter_form'] = FilterForm() context['activestep'] = "1" context['search_message'] = search_message extra_context = {"message": "Updating filter"} context.update(extra_context or {}) return TemplateResponse(request, templates, context) else: context['filter_form'] = form extra_context = {"message":"Something went wrong"} context.update(extra_context or {}) return TemplateResponse(request, templates, context) else: context.update(extra_context or {}) return TemplateResponse(request, templates, context) def child_detail(request, template="pages/sponsorship.html", extra_context=None, pk=None): templates = [] templates.append(template) children = Child.objects.filter(pk=pk) if request.method == "GET": context = {"child_filter": children, "filter_form
how do I handle a dropdown in Django whose only purpose is to get data.
I need to create an edit box called handicapped with three drop down options on the display: 0 - none 1 - Mental 2 - Phyiscal and connect it to the handicapped field init(11) in the family database I know I have to do something like: if form['handicapped'].data == 1 or 2: q = context['child_filter'].filter(Q(handicapped=handicapped_dict[request.POST['handicapped']])) >>> But I'm really confused about the above part. # start of output using search parameters if q.count() > 1: search_message = "There are %s children that match your selection of %s" % (q.count(), request.POST['gender']) else: search_message = "There is 1 child that matches your selection of %s" % (request.POST['gender']) if q.count() > 1: search_message = ", age: %s" % (request.POST['age']) else: search_message = ", age: %s" % (request.POST['age']) if form.data['handicapped'] is 'Physical' or 'Mental': if q.count() > 1: search_message = ", is %s handicapped" % (request.POST['handicapped']) elif q.count() == 1: search_message = ", is %s handicapped" % (request.POST['handicapped']) else: search_message = ", are %s handicapped" % (request.POST['handicapped']) but it doesn't _work at all_. I should say the database is defined correctly. I get lots of different types of errors - sorry I can't include them now, ... I am trying to find the children (already in the database) who may or may not have one of two types of handicaps. I _do_ use Form. The form file contents follow: from django import forms from .widgets import ChainedSelectWidget from .models import Child class SponsorForm(forms.Form): child = forms.IntegerField() class FilterForm(forms.Form): gender = forms.ChoiceField(choices=[(x, x) for x in ('-', 'MALE', 'FEMALE')], required=False) age = forms.ChoiceField(choices=[(x, x) for x in range(1, 18)], required=False) #orphaned = forms.BooleanField(initial=False,required=False) #extreme_need = forms.BooleanField(initial=False,required=False) handicapped = forms.ChoiceField(choices=[(x, x) for x in ('---', 'Mental', 'Physcal')], required=False) def __init__(self, *args, **kwargs): super(FilterForm, self).__init__(*args, **kwargs) if 0 == len(self.data): self.fields['age'].queryset = Child.objects.none() # assign a widget to second select field self.fields['age'].widget = ChainedSelectWidget( parent_name='gender', # the name of parent field app_name='sponsorship',# the name of model's application model_name='child', # the name of a model with the method method_name='get_children', # the name of queryset method ) -Eileen -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a77173e5-8cf4-43bf-81e3-10757ba88ec3%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Need to create an edit box connected to one table field
Yes, I use Form. Here's it's contents: from django import forms from .widgets import ChainedSelectWidget from .models import Child class SponsorForm(forms.Form): child = forms.IntegerField() class FilterForm(forms.Form): gender = forms.ChoiceField(choices=[(x, x) for x in ('-', 'MALE', 'FEMALE')], required=False) age = forms.ChoiceField(choices=[(x, x) for x in range(1, 18)], required=False) #orphaned = forms.BooleanField(initial=False,required=False) #extreme_need = forms.BooleanField(initial=False,required=False) handicapped = forms.ChoiceField(choices=[(x, x) for x in ('---', 'Mental', 'Physcal')], required=False) def __init__(self, *args, **kwargs): super(FilterForm, self).__init__(*args, **kwargs) if 0 == len(self.data): self.fields['age'].queryset = Child.objects.none() # assign a widget to second select field self.fields['age'].widget = ChainedSelectWidget( parent_name='gender', # the name of parent field app_name='sponsorship',# the name of model's application model_name='child', # the name of a model with the method method_name='get_children', # the name of queryset method ) It is for finding a child who may or may not have one of two types of handicaps. -Eileen On Friday, January 19, 2018 at 9:54:15 PM UTC-5, Costja Covtushenko wrote: > > Hi Eileen, > > Can you please elaborate a little bit? > Do you use Form? Can you provide its code? > > Also sorry but it is not clear what are you trying to achieve with those > value? > Is it for searching data in DB? > > Regards, > Constantine C. > > On Jan 19, 2018, at 5:08 PM, eil...@themaii.org wrote: > > handicapped > > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f7cddedd-48b3-4542-8b34-acafb183b02d%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Need to create an edit box connected to one table field
I need to create an edit box called handicapped with three drop down options on the display: 0 - none 1 - Mental 2 - Phyiscal and connect it to the handicapped field init(11) in the family database I know I have to do something like: if form['handicapped'].data == 1 or 2: q = context['child_filter'].filter(Q(handicapped=handicapped_dict[request.POST['handicapped']])) # start of output using search parameters if q.count() > 1: search_message = "There are %s children that match your selection of %s" % (q.count(), request.POST['gender']) else: search_message = "There is 1 child that matches your selection of %s" % (request.POST['gender']) if q.count() > 1: search_message = ", age: %s" % (request.POST['age']) else: search_message = ", age: %s" % (request.POST['age']) if form.data['handicapped'] is 'Physical' or 'Mental': if q.count() > 1: search_message = ", is %s handicapped" % (request.POST['handicapped']) elif q.count() == 1: search_message = ", is %s handicapped" % (request.POST['handicapped']) else: search_message = ", are %s handicapped" % (request.POST['handicapped']) but it doesn't _work at all_. The database is defined all right, I should say. I get lots of different types of errors - sorry I can't include them now, but definitely not week if the problem is still outstanding. -Eileen -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/538b8651-fcf9-4310-abe6-baae7d7b1f56%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.