Django: Math on Models - django

I need to do some math against a value and I'm very confused about F(). I've read through the docs and searched for examples but I'm missing some fundamentals. Could you help with a solution and give some pointers about how to make sense of this? My attempts below are commented out. I'm just trying to convert Mb to GB. If I could get a 2 decimal value that would be be really wonderful.
class DatastoreInfo(models.Model):
[ ... ]
total_capacity = models.IntegerField(db_column='Total_Capacity', blank=True, null=True)
[ ... ]
class Meta:
managed = False
db_table = 'Datastore_Info'
def ecsdatastores(request):
form = myForm()
results = {}
if request.method == 'POST':
if 'listxyz' in request.POST:
form = myForm(request.POST)
taf = form['taf'].value()
results = DatastoreInfo.objects.filter(f_hostname=c_name)
# results = DatastoreInfo.objects.filter(f_hostname=c_name, total_capacity=F('total_capacity') / 1000)
# results = DatastoreInfo.objects.update(total_capacity=F('total_capacity') / 1000).filter(f_hostname=c_name)
return render(request, 'dpre/datastoreinfo.html', {'form': form , 'results': results})

You almost are there. You need to organize your query so first you filter down to the applicable rows, and then you apply the update with the F function as the value.
# First take your filtered rows
results = DatastoreInfo.objects.filter(f_hostname=c_name)
# Then, on the filtered queryset, you can apply the update.
results.update(total_capacity=F('total_capacity') / 1000)
You can see this is just like the reporter example from the Django F Expression Documentation.
reporter = Reporters.objects.filter(name='Tintin')
reporter.update(stories_filed=F('stories_filed') + 1)
Edit: As a side note you may want to divide by 1024, not 1000, if converting from GB to MB.

Related

Flask wtforms AttributeError: 'HTMLString' object has no attribute 'paginate'

Somebody has helped me with some great code here to show the same form multiple times each with a submit button, it works a treat, But as I will have hundreds of forms I need to paginate the page, I have been able to paginate pages in the past but I dont no how to use that code with a form in a for loop.
here is my code:(with lots of help from Greg)
#bp.route('/stock', methods=['GET', 'POST'])
#bp.route('/stock/stock/', methods=['GET', 'POST'])
#login_required
def stock():
stocks = Stock.query.all()
forms = []
for stock in stocks:
form = AddStockForm()
form.id.default = stock.id
form.image.default = stock.image_url
form.date.default = stock.date
form.description.default = stock.description
form.event.default = stock.event
form.achat.default = stock.achat
form.vente.default = stock.vente
form.sold.default = stock.sold
forms.append(form)
for form in forms:
if form.validate_on_submit():
if form.modify.data:
stock = Stock.query.filter_by(id=form.id.data).one()
stock.date = form.date.data
stock.description = form.description.data
stock.event = form.event.data
stock.achat = form.achat.data
stock.vente = form.vente.data
stock.sold = form.sold.data
db.session.add(stock)
db.session.commit()
elif form.delete.data:
stock = Stock.query.filter_by(id=form.id.data).one()
db.session.delete(stock)
db.session.commit()
return redirect(url_for('stock.stock'))
form.process() # Do this after validate_on_submit or breaks CSRF token
page = request.args.get('page', 1, type=int)
forms = forms[1].id().paginate(
page, current_app.config['ITEMS_PER_PAGE'], False)
next_url = url_for('stock.stock', page=forms.next_num) \
if forms.has_next else None
prev_url = url_for('stock.stock', page=forms.prev_num) \
if forms.has_prev else None
return render_template('stock/stock.html',forms=forms.items, title=Stock, stocks=stocks)
I am trying to use the fact "forms" is a list to paginate the results, I obviously dont understand how to do this, I have looked at flask-paginate but I didnt understand that either!
all help is greatly needed
Warm regards, Paul.
EDIT
I have tried to use flask_pagination, here is my code:
#bp.route('/stock/stock/', methods=['GET', 'POST'])
#login_required
def stock():
search = False
q = request.args.get('q')
if q:
search = True
page = request.args.get(get_page_parameter(), type=int, default=1)
stocks = Stock.query.all()
forms = []
#rest of code here#
pagination = Pagination(page=page, total=stocks.count(), search=search, record_name='forms')
form.process() # Do this after validate_on_submit or breaks CSRF token
return render_template('stock/stock.html',forms=forms, title=Stock, pagination=pagination)
This gives a different error "TypeError: count() takes exactly one argument (0 given)" I also tried with "total=forms.count()" and got the same error!
I hate doing this as it shows a lack of patience at the begining but this answer may help others, I solved my problem in two ways the first was the query which decides the order of display (descending or ascending) this then allowed me to use flask-paginate to display the results on several pages, I realised that I was dealing with a list, and the example by one of the developers link showed me the way, here is my code,
from flask_paginate import Pagination, get_page_args
#bp.route('/stock', methods=['GET', 'POST'])
#bp.route('/stock/stock/', methods=['GET', 'POST'])
#login_required
def stock():
stocks = Stock.query.order_by(Stock.id.desc())# this gives order of results
forms = []
def get_forms(offset=0, per_page=25): #this function sets up the number of
return forms[offset: offset + per_page] #results per page
for stock in stocks:
form = AddStockForm()
form.id.default = stock.id
form.image.default = stock.image_url
form.date.default = stock.date
form.description.default = stock.description
form.event.default = stock.event
form.achat.default = stock.achat
form.vente.default = stock.vente
form.sold.default = stock.sold
forms.append(form)
for form in forms:
if form.validate_on_submit():
if form.modify.data:
stock = Stock.query.filter_by(id=form.id.data).one()
stock.date = form.date.data
stock.description = form.description.data
stock.event = form.event.data
stock.achat = form.achat.data
stock.vente = form.vente.data
stock.sold = form.sold.data
db.session.add(stock)
db.session.commit()
elif form.delete.data:
stock = Stock.query.filter_by(id=form.id.data).one()
db.session.delete(stock)
db.session.commit()
return redirect(url_for('stock.stock'))
#this is the code from the link that I used to paginate
page, per_page, offset = get_page_args(page_parameter='page',
per_page_parameter='per_page')
total = len(forms) # this code counts the resulting list to be displayed
pagination_forms = get_forms(offset=offset, per_page=per_page)
pagination = Pagination(page=page, per_page=per_page, total=total)
form.process() # Do this after validate_on_submit or breaks CSRF token
return render_template('stock/stock.html', title=Stock, stocks=stocks
page=page, forms=pagination_forms, per_page=per_page, pagination=pagination)
#And finally this is the pagination passed to the html
so this for all those numptys like me who struggle with everything but still love it.

Django inline-formset ordering issue when editing

I am trying to use the Django inline-formset.
Forms should be displayed sorted by their order value which is correctly done when I request the form.
But if I change the order values and save, the first view is with the previous order (refresh does the trick)
forms:
class SlidesForm(forms.ModelForm):
order = forms.IntegerField(widget=forms.NumberInput())
background_image = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'}), required=False)
text = forms.CharField(max_length=256, widget=forms.Textarea(attrs={'rows': 2, 'class': 'form-control'}), required=False)
class Meta:
model = SlideCarousel
fields = ['order', 'background_image', 'text']
views:
def management_form_general(request, city_slug):
city = City.objects.get(slug=city_slug)
SlideCarouselInlineFormSet = inlineformset_factory(City, SlideCarousel, form=SlidesForm, extra=0)
if request.method == 'POST':
carousel_formset = SlideCarouselInlineFormSet(request.POST, request.FILES, instance=city, queryset=city.slidecarousel_set.order_by("order"))
if carousel_formset.is_valid():
carousel_formset.save()
else:
carousel_formset = SlideCarouselInlineFormSet(instance=city, queryset=city.slidecarousel_set.order_by("order"))
return render(request, 'management/form/city_general.html', {'city': city, 'carousel_formset': carousel_formset})
Any idea what I am doing wrong ? Tried to reinstance the carousel_formset after the save but it seems nasty and it actually didn't work
Right now you're still returning the same queryset (already evaluated and ordered) in the formset. What you need is to get the data that you just saved and update the formset with it. I think that you have two options that should work.
Recreate the carousel_formset like you said. This might not be exactly what you want but it seems more likely than my second suggestion. You said you tried this and it didn't work. If your code looks the same as mine then you might want to skip this approach.
carousel_formset.save()
carousel_formset = SlideCarouselInlineFormSet(
instance=city,
queryset=city.slidecarousel_set.order_by("order"),
)
Usually, after I save a form(set) I would redirect to a success URL. In this case that would be the same path again.
carousel_formset.save()
return redirect(request.path)
A third option that I have no idea if it will work, but you could try for very little effort, would be to re-set the carousel_formset.queryset attribute.
carousel_formset.save()
carousel_formset.queryset = city.slidecarousel_set.order_by("order")

Django2.2 Context Manager | {{template_tags}} | Variable limit?

I have a template view in Django2.2, where I added two models & queries to look up metrics on user data (how many articles they read each month).
I ran into a strange issue where if I place multiple context variables on the page, every variable on the page but the First Variable will return '0'. If I simply change the order of the variables in the markup, each date function appears to be calculating correctly (as long as it is the first to appear). I couldn't find anything about this in the docs...and I'm guessing that this isn't a great approach to display this information either and I should instead use a DjangoTemplateTag and perform the operations there.
*Define the Object & Query
def get_context_data(self, **kwargs):
context = super(userDashBoardView, self).get_context_data(**kwargs)
context['readArticleList'] = Articles.objects.filter(Unread = False,userId = self.request.user.SFPK )
*To avoid making further queries, I mutated the query into a set to perform further functions
article_list = set(context['readArticleList'])
article_read_date = (article_list.read_date for article_list in article_list)
context['articles_last30'] = len(set(x for x in article_read_date if x > timezone.now() - timedelta(days=30)))
context['articles_last60'] = len(set(x for x in article_read_date if x > timezone.now() - timedelta(days=60)))
context['articles_last90'] = len(set(x for x in article_read_date if x > timezone.now() - timedelta(days=90)))
return context
{% block content %}
{{articles_last30}}
{{articles_last60}}
{{articles_last90}}
{% endblock %}
<br/>
For context,context,context in the example above *using sample data
the output on the page is (4,0,0)
If the order is reversed, I get
(20,0,0)
NOTE: I am NOT receiving any errors in the console, and the page(s) are loading fine. Can anyone point me in the right direction?
-Thank you for your time =)
You use a generator for article_read_date, indeed:
article_read_date = (article_list.read_date for article_list in article_list)
This means that after you have iterated over it, the generator is "exhausted". Another loop over the iterator will not yield any values anymore. An illustrative example is the following:
>>> l = [1,4,2,5]
>>> g = (x for x in l)
>>> list(g)
[1, 4, 2, 5]
>>> list(g)
[]
as you can see, the second list(g) does not produces any values anymore.
You can create a set with:
article_read_date = [a.read_date for a in context['readArticleList']]
def count_since(iterable, _timed):
timestamp = timezone.now() - timed
return sum(x > timestamp for x in iterable)
context['articles_last30'] = count_since(article_read_date, timedelta(days=30))
context['articles_last60'] = count_since(article_read_date, timedelta(days=60))
context['articles_last90'] = count_since(article_read_date, timedelta(days=90))
That being said, since django-2.0, Count [Django-doc] has a filter= attribute, so you can count the articles with one extra query like:
from django.db.models import Count, Q
nw = timezone.now()
context.update(
context['readArticleList'].aggregate(
articles_last30=Count('pk', filter=Q(read_date__gt=nw-timedelta(days=30))),
articles_last60=Count('pk', filter=Q(read_date__gt=nw-timedelta(days=60))),
articles_last90=Count('pk', filter=Q(read_date__gt=nw-timedelta(days=90)))
)
)
You can do what you are doing in a much more efficient way and cleaner way.
First though you should Note that the convention is models are not named in plural. So it is not Articles.objects.. but Article.objects... You should rename your model to Article instead of Articles.
If we assume that as should be the case that Article(s) is a model which has field read date.
class Article(models.Model):
read_date = models.DateTimeField()
... other_fields ..
Since you very much want efficiency. You can count the results straight from the DB.
def get_context_data(self, **kwargs):
thirty_days_ago = datetime.now() - timedelta(days=30)
sixty_days_ago = datetime.now() - timedelta(day=60)
ninty_days_ago = datetime.now() - timedelta(day=90)
ctx = super().get_context_data(**kwargs)
ctx['articles_last90'] = \
Article.objects.filter(read_date__gt=ninty_days_ago).count()
ctx['articles_last60'] = \
Article.objects.filter(read_date__gt=sixty_days_ago).count()
ctx['last_last30'] = \
Article.objects.filter(read_date__gt=thirty_days_ago).count()
return ctx
This way you never ever load anything into python memory except the number of articles. It is much better than iterating or even using len(list_of_items).
You just have to be conscious of that read_time__gt=ninty_days_ago means articles that were last read more than ninty days ago.
See more from Django Docs.

Django formset unit test

I can't run a unit test with formset.
I try to do a test:
class NewClientTestCase(TestCase):
def setUp(self):
self.c = Client()
def test_0_create_individual_with_same_adress(self):
post_data = {
'ctype': User.CONTACT_INDIVIDUAL,
'username': 'dupond.f',
'email': 'new#gmail.com',
'password': 'pwd',
'password2': 'pwd',
'civility': User.CIVILITY_MISTER,
'first_name': 'François',
'last_name': 'DUPOND',
'phone': '+33 1 34 12 52 30',
'gsm': '+33 6 34 12 52 30',
'fax': '+33 1 34 12 52 30',
'form-0-address1': '33 avenue Gambetta',
'form-0-address2': 'apt 50',
'form-0-zip_code': '75020',
'form-0-city': 'Paris',
'form-0-country': 'FRA',
'same_for_billing': True,
}
response = self.c.post(reverse('client:full_account'), post_data, follow=True)
self.assertRedirects(response, '%s?created=1' % reverse('client:dashboard'))
and I have this error:
ValidationError: [u'ManagementForm data is missing or has been
tampered with']
My view :
def full_account(request, url_redirect=''):
from forms import NewUserFullForm, AddressForm, BaseArticleFormSet
fields_required = []
fields_notrequired = []
AddressFormSet = formset_factory(AddressForm, extra=2, formset=BaseArticleFormSet)
if request.method == 'POST':
form = NewUserFullForm(request.POST)
objforms = AddressFormSet(request.POST)
if objforms.is_valid() and form.is_valid():
user = form.save()
address = objforms.forms[0].save()
if url_redirect=='':
url_redirect = '%s?created=1' % reverse('client:dashboard')
logon(request, form.instance)
return HttpResponseRedirect(url_redirect)
else:
form = NewUserFullForm()
objforms = AddressFormSet()
return direct_to_template(request, 'clients/full_account.html', {
'form':form,
'formset': objforms,
'tld_fr':False,
})
and my form file :
class BaseArticleFormSet(BaseFormSet):
def clean(self):
msg_err = _('Ce champ est obligatoire.')
non_errors = True
if 'same_for_billing' in self.data and self.data['same_for_billing'] == 'on':
same_for_billing = True
else:
same_for_billing = False
for i in [0, 1]:
form = self.forms[i]
for field in form.fields:
name_field = 'form-%d-%s' % (i, field )
value_field = self.data[name_field].strip()
if i == 0 and self.forms[0].fields[field].required and value_field =='':
form.errors[field] = msg_err
non_errors = False
elif i == 1 and not same_for_billing and self.forms[1].fields[field].required and value_field =='':
form.errors[field] = msg_err
non_errors = False
return non_errors
class AddressForm(forms.ModelForm):
class Meta:
model = Address
address1 = forms.CharField()
address2 = forms.CharField(required=False)
zip_code = forms.CharField()
city = forms.CharField()
country = forms.ChoiceField(choices=CountryField.COUNTRIES, initial='FRA')
In particular, I've found that the ManagmentForm validator is looking for the following items to be POSTed:
form_data = {
'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0
}
Every Django formset comes with a management form that needs to be included in the post. The official docs explain it pretty well. To use it within your unit test, you either need to write it out yourself. (The link I provided shows an example), or call formset.management_form which outputs the data.
It is in fact easy to reproduce whatever is in the formset by inspecting the context of the response.
Consider the code below (with self.client being a regular test client):
url = "some_url"
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
# data will receive all the forms field names
# key will be the field name (as "formx-fieldname"), value will be the string representation.
data = {}
# global information, some additional fields may go there
data['csrf_token'] = response.context['csrf_token']
# management form information, needed because of the formset
management_form = response.context['form'].management_form
for i in 'TOTAL_FORMS', 'INITIAL_FORMS', 'MIN_NUM_FORMS', 'MAX_NUM_FORMS':
data['%s-%s' % (management_form.prefix, i)] = management_form[i].value()
for i in range(response.context['form'].total_form_count()):
# get form index 'i'
current_form = response.context['form'].forms[i]
# retrieve all the fields
for field_name in current_form.fields:
value = current_form[field_name].value()
data['%s-%s' % (current_form.prefix, field_name)] = value if value is not None else ''
# flush out to stdout
print '#' * 30
for i in sorted(data.keys()):
print i, '\t:', data[i]
# post the request without any change
response = self.client.post(url, data)
Important note
If you modify data prior to calling the self.client.post, you are likely mutating the DB. As a consequence, subsequent call to self.client.get might not yield to the same data, in particular for the management form and the order of the forms in the formset (because they can be ordered differently, depending on the underlying queryset). This means that
if you modify data[form-3-somefield] and call self.client.get, this same field might appear in say data[form-8-somefield],
if you modify data prior to a self.client.post, you cannot call self.client.post again with the same data: you have to call a self.client.get and reconstruct data again.
Django formset unit test
You can add following test helper methods to your test class [Python 3 code]
def build_formset_form_data(self, form_number, **data):
form = {}
for key, value in data.items():
form_key = f"form-{form_number}-{key}"
form[form_key] = value
return form
def build_formset_data(self, forms, **common_data):
formset_dict = {
"form-TOTAL_FORMS": f"{len(forms)}",
"form-MAX_NUM_FORMS": "1000",
"form-INITIAL_FORMS": "1"
}
formset_dict.update(common_data)
for i, form_data in enumerate(forms):
form_dict = self.build_formset_form_data(form_number=i, **form_data)
formset_dict.update(form_dict)
return formset_dict
And use them in test
def test_django_formset_post(self):
forms = [{"key1": "value1", "key2": "value2"}, {"key100": "value100"}]
payload = self.build_formset_data(forms=forms, global_param=100)
print(payload)
# self.client.post(url=url, data=payload)
You will get correct payload which makes Django ManagementForm happy
{
"form-INITIAL_FORMS": "1",
"form-TOTAL_FORMS": "2",
"form-MAX_NUM_FORMS": "1000",
"global_param": 100,
"form-0-key1": "value1",
"form-0-key2": "value2",
"form-1-key100": "value100",
}
Profit
There are several very useful answers here, e.g. pymen's and Raffi's, that show how to construct properly formatted payload for a formset post using the test client.
However, all of them still require at least some hand-coding of prefixes, dealing with existing objects, etc., which is not ideal.
As an alternative, we could create the payload for a post() using the response obtained from a get() request:
def create_formset_post_data(response, new_form_data=None):
if new_form_data is None:
new_form_data = []
csrf_token = response.context['csrf_token']
formset = response.context['formset']
prefix_template = formset.empty_form.prefix # default is 'form-__prefix__'
# extract initial formset data
management_form_data = formset.management_form.initial
form_data_list = formset.initial # this is a list of dict objects
# add new form data and update management form data
form_data_list.extend(new_form_data)
management_form_data['TOTAL_FORMS'] = len(form_data_list)
# initialize the post data dict...
post_data = dict(csrf_token=csrf_token)
# add properly prefixed management form fields
for key, value in management_form_data.items():
prefix = prefix_template.replace('__prefix__', '')
post_data[prefix + key] = value
# add properly prefixed data form fields
for index, form_data in enumerate(form_data_list):
for key, value in form_data.items():
prefix = prefix_template.replace('__prefix__', f'{index}-')
post_data[prefix + key] = value
return post_data
The output (post_data) will also include form fields for any existing objects.
Here's how you might use this in a Django TestCase:
def test_post_formset_data(self):
url_path = '/my/post/url/'
user = User.objects.create()
self.client.force_login(user)
# first GET the form content
response = self.client.get(url_path)
self.assertEqual(HTTPStatus.OK, response.status_code)
# specify form data for test
test_data = [
dict(first_name='someone', email='someone#email.com', ...),
...
]
# convert test_data to properly formatted dict
post_data = create_formset_post_data(response, new_form_data=test_data)
# now POST the data
response = self.client.post(url_path, data=post_data, follow=True)
# some assertions here
...
Some notes:
Instead of using the 'TOTAL_FORMS' string literal, we could import TOTAL_FORM_COUNT from django.forms.formsets, but that does not seem to be public (at least in Django 2.2).
Also note that the formset adds a 'DELETE' field to each form if can_delete is True. To test deletion of existing items, you can do something like this in your test:
...
post_data = create_formset_post_data(response)
post_data['form-0-DELETE'] = True
# then POST, etc.
...
From the source, we can see that there is no need include MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT in our test data:
MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are output with the rest of the management form, but only for the convenience of client-side code. The POST value of them returned from the client is not checked.
This doesn't seem to be a formset at all. Formsets will always have some sort of prefix on every POSTed value, as well as the ManagementForm that Bartek mentions. It might have helped if you posted the code of the view you're trying to test, and the form/formset it uses.
My case may be an outlier, but some instances were actually missing a field set in the stock "contrib" admin form/template leading to the error
"ManagementForm data is missing or has been tampered with"
when saved.
The issue was with the unicode method (SomeModel: [Bad Unicode data]) which I found investigating the inlines that were missing.
The lesson learned is to not use the MS Character Map, I guess. My issue was with vulgar fractions (¼, ½, ¾), but I'd assume it could occur many different ways. For special characters, copying/pasting from the w3 utf-8 page fixed it.
postscript-utf-8

Django custom form validation best practices?

I have a form that contains 5 pairs of locations and descriptions. I have three sets of validations that need to be done
you need to enter at least one location
for the first location, you must have a description
for each remaining pair of locations and description
After reading the Django documentation, I came up with the following code to do these custom validations
def clean(self):
cleaned_data = self.cleaned_data
location1 = cleaned_data.get('location1')
location2 = cleaned_data.get('location2')
location3 = cleaned_data.get('location3')
location4 = cleaned_data.get('location4')
location5 = cleaned_data.get('location5')
description1 = cleaned_data.get('description1')
description2 = cleaned_data.get('description2')
description3 = cleaned_data.get('description3')
description4 = cleaned_data.get('description4')
description5 = cleaned_data.get('description5')
invalid_pairs_msg = u"You must specify a location and description"
# We need to make sure that we have pairs of locations and descriptions
if not location1:
self._errors['location1'] = ErrorList([u"At least one location is required"])
if location1 and not description1:
self._errors['description1'] = ErrorList([u"Description for this location required"])
if (description2 and not location2) or (location2 and not description2):
self._errors['description2'] = ErrorList([invalid_pairs_msg])
if (description3 and not location3) or (location3 and not description3):
self._errors['description3'] = ErrorList([invalid_pairs_msg])
if (description4 and not location4) or (location4 and not description4):
self._errors['description4'] = ErrorList([invalid_pairs_msg])
if (description5 and not location5) or (location5 and not description5):
self._errors['description5'] = ErrorList([invalid_pairs_msg])
return cleaned_data
Now, it works but it looks really ugly. I'm looking for a more "Pythonic" and "Djangoist"(?) way to do this. Thanks in advance.
First thing you can do is simplify your testing for those cases where you want to see if only one of the two fields is populated. You can implement logical xor this way:
if bool(description2) != bool(location2):
or this way:
if bool(description2) ^ bool(location2):
I also think this would be more clear if you implemented a clean method for each field separately, as explained in the docs. This makes sure the error will show up on the right field and lets you just raise a forms.ValidationError rather than accessing the _errors object directly.
For example:
def _require_together(self, field1, field2):
a = self.cleaned_data.get(field1)
b = self.cleaned_data.get(field2)
if bool(a) ^ bool(b):
raise forms.ValidationError(u'You must specify a location and description')
return a
# use clean_description1 rather than clean_location1 since
# we want the error to be on description1
def clean_description1(self):
return _require_together('description1', 'location1')
def clean_description2(self):
return _require_together('description2', 'location2')
def clean_description3(self):
return _require_together('description3', 'location3')
def clean_description4(self):
return _require_together('description4', 'location4')
def clean_description5(self):
return _require_together('description5', 'location5')
In order to get the behavior where location1 is required, just use required=True for that field and it'll be handled automatically.
At least you can reduce some code. Have 'location1' and 'description1' Required=True (as TM and stefanw pointed out). Then,
def clean(self):
n=5
data = self.cleaned_data
l_d = [(data.get('location'+i),data.get('description'+i)) for i in xrange(1,n+1)]
invalid_pairs_msg = u"You must specify a location and description"
for i in xrange(1,n+1):
if (l_d[i][1] and not l_d[i][0]) or (l_d[i][0] and not l_d[i][1]):
self._errors['description'+i] = ErrorList([invalid_pairs_msg])
return data
still ugly though...