Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Add batch #66

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions sau/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_queryset(self, request):
return qs.filter(farmers__in=[request.user])


class SheepForm(FarmAwareModelAdmin):
class SheepFormAdmin(FarmAwareModelAdmin):
"""Sheep form, for overriding various fields in admin panel.

Today we override:
Expand All @@ -37,7 +37,7 @@ def __sheep_parent_filter(self, db_field, request, **kwargs):
raise RuntimeError(
'Filter called on wrong field: %s' % str(db_field.name))
kwargs['queryset'] = Sheep.objects.filter(**filters)
return super(SheepForm, self).formfield_for_foreignkey(
return super().formfield_for_foreignkey(
db_field, request, **kwargs)

# To get user-aware dropdown list for farm of a sheep
Expand All @@ -48,7 +48,7 @@ def __farm_filter(self, db_field, request, **kwargs):
if not request.user.is_superuser:
filters['farmers__in'] = [request.user]
kwargs['queryset'] = Farm.objects.filter(**filters)
return super(SheepForm, self).formfield_for_foreignkey(
return super().formfield_for_foreignkey(
db_field, request, **kwargs)

# this is the method we're overriding, but only on fields
Expand All @@ -59,11 +59,11 @@ def formfield_for_foreignkey(self, db_field, request, **kwargs):
return self.__sheep_parent_filter(db_field, request, **kwargs)
if db_field.name == 'farm':
return self.__farm_filter(db_field, request, **kwargs)
return super(SheepForm, self).formfield_for_foreignkey(
return super().formfield_for_foreignkey(
db_field, request, **kwargs)


admin.site.register(Sheep, SheepForm)
admin.site.register(Sheep, SheepFormAdmin)
admin.site.register(Medicine)
admin.site.register(Dose)
admin.site.register(Farm, FarmAwareModelAdmin)
15 changes: 15 additions & 0 deletions sau/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,18 @@ def __init__(self, *args, **kwargs):
self.fields['father'].queryset = Sheep.objects.filter(sex='m') # male
self.fields['mother'].queryset = Sheep.objects.filter(sex='f') # female
self.fields['birth_date_utc'].required = True


class SheepBatchForm(forms.Form):
rams = forms.IntegerField()
ewes = forms.IntegerField()
birth_date_utc = forms.CharField()

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
#self.fields['father'].queryset = Sheep.objects.filter(sex='m') # male
#self.fields['mother'].queryset = Sheep.objects.filter(sex='f') # female


def save(self, commit=True):
return super().save(commit=commit)
4 changes: 3 additions & 1 deletion sau/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ <h1 class="page-title">{% block page_title %}<a href="{% url 'index' %}">Sau2000
{% block content %}
<div class="content-box">

<h2 class="farm-name">{{farm.name}} <a href="{% url 'new_sheep' %}">(+)</a></h2>
<h2 class="farm-name">{{farm.name}} <a href="{% url 'new_sheep' %}">(+)</a>
<a href="{% url 'new_sheep_batch' %}">(++)</a>
</h2>

{% if is_search %}
<ul class="messages search">
Expand Down
30 changes: 30 additions & 0 deletions sau/templates/sau_add_batch.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{% extends 'index.html' %}
{% load humanize %}

{% block breadcrumb %}
<li><span>New batch</span></li>
{% endblock %}

{% block content %}

<div class="content-box">
<h2>New Sheep batch</h2>

<form class="pure-form pure-form-stacked{% if form.errors %} form-errors{% endif %}" method="POST">
{% csrf_token %}
<fieldset>
<ul class="form-list">
{% for field in form.visible_fields %}
{% include 'partials/form_field.html' with field=field %}
{% endfor %}
</ul>
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<input type="submit" value="Save" />
</fieldset>
</form>
</div>


{% endblock %}
1 change: 1 addition & 0 deletions sau/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
url(r'^$', views.index, name='index'),
url(r'^stats$', views.stats, name='stats'), # this can later be stats/2016
url(r'^new/', views.create_or_edit_sheep, name='new_sheep'),
url(r'^new_batch/', views.add_sheep_batch, name='add_sheep_batch'),
url(r'^sau/(?P<slug>[-\w]{1,255})/(?P<sheep_id>\d+)$', views.sau, name='sau'),
url(r'^sau/(?P<slug>[-\w]{1,255})/(?P<sheep_id>\d+)/dose', views.add_dose, name='dose'),
url(r'^sau/(?P<slug>[-\w]{1,255})/(?P<sheep_id>\d+)/edit', views.create_or_edit_sheep, name='edit_sheep'),
Expand Down
2 changes: 1 addition & 1 deletion sau/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
get_weight_per_year)

from .views_util import _get_sheep_or_404
from .views_editors import add_dose, create_or_edit_sheep
from .views_editors import add_dose, create_or_edit_sheep, add_sheep_batch


def get_all_sheep(request, *, filter_=None):
Expand Down
41 changes: 40 additions & 1 deletion sau/views_editors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from django.utils.translation import gettext as _
from django.urls import reverse

from .forms import DoseForm, SheepForm
from .forms import DoseForm, SheepForm, SheepBatchForm

from .views_util import _get_sheep_or_404, _get_sheep

Expand Down Expand Up @@ -133,3 +133,42 @@ def _edit_sheep(request, sheep):
'form': form,
'sheep': sheep
})

def _save_sheep_batch(request, form):
data = form.cleaned_data
mother, father, = data.get('mother', None), data.get('father', None)
birth_date_utc = data['birth_date_utc']
try:
rams, ewes = int(data['rams'].value), int(data['ewes'].value)
except ValueError:
raise ValueError('rams and ewes must be integer in batch form')
batch = Sheep.batch(farm,
mother=mother,
father=father,
ewes=ewes,
rams=rams,
birth_date_utc=_date_with_now_time(birth_date_utc))
return batch


def add_sheep_batch(request):
if request.method == "POST":
form = SheepBatchForm(request.POST)
if form.is_valid():
batch = _save_sheep_batch(request, form)
rams = len([x for x in batch if x.sex == 'm'])
ewes = len(batch) - len(rams)
messages.success(request,
'Created %d rams, %d ewes. <a href="%s">Add another.</a>' %
(sheep.name, reverse('add_sheep_batch')))
return redirect('index')
# If form was not valid, it needs to be returned as-is, since it keeps
# track of the errors.
else:
messages.error(request,
_('Form had errors, could not create batch.'))

elif request.method == "GET":
form = SheepBatchForm()

return TemplateResponse(request, 'sau_add_batch.html', context={'form': form})