It it possible ? I want compare two fields and return score to bet_score field.
class Tabela(models.Model):
score1= models.IntegerField(max_length=3)
score2 = models.IntegerField(max_lenght=3)
bet_score= models.IntegerField(defaults=bet_score())
def bet_score(self):
if (self.score1> self.score2 ):
return 1
elif (self.score1== self.score2 ):
return 0
else:
return 2
If you want to store this kind of thing on a model, I think your best option would be to override the save method:
class Tabela(models.Model):
score1= models.IntegerField(max_length=3)
score2 = models.IntegerField(max_lenght=3)
bet_score= models.IntegerField()
def save(self, *args, **kwargs):
if (self.score1 > self.score2 ):
self.bet_score = 1
elif (self.score1 == self.score2 ):
self.bet_score = 0
else:
self.bet_score = 2
super(Tabela, self).save(*args, **kwargs)
Check out the docs for more info.
Related
I want to create a model, which is symmetric on two fields. Let's call the model Balance:
class Balance (models.Model):
payer = models.ForeignKey(auth.User, ...)
payee = models.ForeignKey(auth.User, ...)
amount = models.DecimalField(...)
It should have the following property:
balance_forward = Balance.objects.get(payer=USER_1, payee=USER_2)
balance_backward = Balance.objects.get(payer=USER_2, payee=USER_1)
balance_forward.amount == -1 * balance_backward.amount
What is the best way to implement this?
You can aggregate on the Balance objects with:
from django.db.models import Case, F, Sum, When
from django.conf import settings
class Balance(models.Model):
payer = models.ForeignKey(settings.AUTH_USER_MODEL, …)
payee = models.ForeignKey(settings.AUTH_USER_MODEL, …)
amount = models.DecimalField(…)
def get_balance(cls, payer, payee):
return cls.objects.filter(
Q(payer=payer, payee=payee) | Q(payer=payee, payee=payer)
).aggregate(
total=Sum(
Case(
When(payer=payer, then=F('amount')),
otherwise=-F('amount'),
output_field=DecimalField(…),
)
)
)['total']
This will look for all Balances between the payer and the payee, and subtract the ones in the opposite direction. The Balance.get_balance(payer=foo, payee=bar) will thus determine the total flow from foo to bar.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
So, I came up with the following solution. Feel free to suggest other solutions.
class SymmetricPlayersQuerySet (models.query.QuerySet):
def do_swap(self, obj):
obj.payer, obj.payee = obj.payee, obj.payer
obj.amount *= -1
def get(self, **kwargs):
swap = False
if "payer" in kwargs and "payee" in kwargs:
if kwargs["payer"].id > kwargs["payee"].id:
swap = True
kwargs["payer"], kwargs["payee"] = \
kwargs["payee"], kwargs["payer"]
obj = super().get(**kwargs)
if swap:
self.do_swap(obj)
return obj
def filter(self, *args, **kwargs):
if (
("payer" in kwargs and "payee" not in kwargs) or
("payee" in kwargs and "payer" not in kwargs)
):
if "payee" in kwargs:
key, other = "payee", "payer"
else:
key, other = "payer", "payee"
constraints = (
models.Q(payer=kwargs[key]) |
models.Q(payee=kwargs[key])
)
queryset = super().filter(constraints)
for obj in queryset:
if getattr(obj, other) == kwargs[key]:
self.do_swap(obj)
return queryset
return super().filter(*args, **kwargs)
class BalanceManager (models.Manager.from_queryset(SymmetricPlayersQuerySet)):
pass
class Balance (models.Model):
objects = BalanceManager()
payer = models.ForeignKey(
Player,
on_delete=models.CASCADE,
related_name='balance_payer',
)
payee = models.ForeignKey(
Player,
on_delete=models.CASCADE,
related_name='balance_payee',
)
amount = models.DecimalField(decimal_places=2, max_digits=1000, default=0)
def do_swap(self):
self.payer, self.payee = self.payee, self.payer
self.amount *= -1
def save(self, *args, **kwargs):
swap = False
if self.payer.id > self.payee.id:
swap = True
self.do_swap()
result = super().save(*args, **kwargs)
if swap:
self.do_swap()
return result
def refresh_from_db(self, *args, **kwargs):
swap = False
if self.payer.id > self.payee.id:
swap = True
super().refresh_from_db(*args, **kwargs)
if swap:
self.do_swap()
I am trying to adjust the cleaned_data that I get from the modelform to save certain values to the model based on the users input. These inputs can vary greatly, please see the model below along with the forms and views.
Should I call the model methods into the model form or should I do all the calculations in the modelForm itself. The figures can change depending on the contract selected and the start date selected as it will count the number of days and base it on this price for the contract, however if it is a half day then it will just divide the number by 2.
I am still new to Django but trying to figure out where all this information should be put, I am certainly clueless on this and trying to learn Django myself through real lifelike applications instead so appreciate your help.
Model
class AdminData(models.Model):
year1 = models.IntegerField()
year3 = models.IntegerField()
year1_fortnight = models.IntegerField()
year3_fortnight = models.IntegerField()
#property
def fortnight_dayrate_year1(self):
return self.year1_fortnight / weeksinyear / 5
#property
def fortnight_dayrate_year3(self):
return self.year3_fortnight / weeksinyear / 5
#property
def day_rate_year1(self):
return self.year1 / weeksinyear / 5
#property
def day_rate_year3(self):
return self.year3 / weeksinyear / 5
class Price(models.Model):
year_choice = Choices('1-Year Weekly', '3-Year Weekly','1-Year Fortnightly', '3-Year Fortnightly')
day_choice = Choices('Full Day', 'Half Day')
name = models.CharField(max_length=100)
contract = StatusField(choices_name='year_choice')
time_daily = StatusField(choices_name='day_choice')
start_date = models.DateField(default=datetime.now)
end_date = models.DateField(default=datetime(2021,3,31))
weeksinyear = 52
hours = 6.5
epoch_year = date.today().year
year_start = date(epoch_year, 1, 4)
year_end = date(epoch_year, 3, 31)
#property
def day_count(self):
return year_end - self.start_date
# #property
# def price_year1_weekly(self):
# if self.contract == self.year_choice[0]
# return AdminData.year1 * self.day_count
def __str__(self):
return self.name
Forms.py
class PriceForm(forms.ModelForm):
class Meta:
model = Price
fields = ['name', 'contract','time_daily','start_date']
Views.py
def price_detail(request):
if request.method == 'POST':
form = PriceForm(request.POST)
if form.is_valid():
price_instance = form.cleaned_data
form.save()
return render(request,'confirmation.html',{'form_data': price_instance})
else:
form = PriceForm()
return render(request, 'main.html', {'form': form})
For at the time of transaction calculations, the views.py is a good place for this, ie. a purchase, where the price is agreed upon at that moment and will never change.
If the business logic requires that the data updates the transaction, then the model is better.
views.py
def price_detail(request):
form = PriceForm(request.POST or None)
if form.is_valid():
price_instance = form.save() // this returns a saved instance
... do calculations here ...
price_instance.calculated_field = 1 + 1 // example calculations
price_instance.confirmed = False // consider adding a confirmed boolean, to not allow users to alter the data in the next step.
price_instance.save()
return render(request, 'confirmation.html', {'price_instance': price_instance})
else:
return render(request, 'main.html', {'form': form})
An example of doing the calculations every time the model is saved by overriding the model's save() method.
models.py
class Price(models.Model):
year_choice = Choices('1-Year Weekly', '3-Year Weekly','1-Year Fortnightly', '3-Year Fortnightly')
day_choice = Choices('Full Day', 'Half Day')
name = models.CharField(max_length=100)
contract = StatusField(choices_name='year_choice')
time_daily = StatusField(choices_name='day_choice')
start_date = models.DateField(default=datetime.now)
end_date = models.DateField(default=datetime(2021,3,31))
weeksinyear = 52
hours = 6.5
epoch_year = date.today().year
year_start = date(epoch_year, 1, 4)
year_end = date(epoch_year, 3, 31)
#property
def day_count(self):
return year_end - self.start_date
def save(self, *args, **kwargs):
... do calculations here ...
self.calculated_field = 1 + 1 // calculations
super().save(*args, **kwargs)
def __str__(self):
return self.name
I am trying to render a generic detail view page with a form with errors
My post method in my generic detail view is
def post(self, request, slug):
if 'submit-edit-roster' in request.POST:
edit_roster_form = EditRosterForm(request.POST, team=self.request.user.playerprofile.team)
if edit_roster_form.is_valid():
edit_roster_form.save()
return redirect ('tcl-team', slug=self.request.user.playerprofile.team.urlslug)
my edit roster form is
class EditRosterForm(forms.Form):
members = 0
team = None
sublist = []
playerlist = []
def __init__(self, *args, **kwargs):
self.team = kwargs.pop('team', None)
self.members = 0
self.sublist = []
self.playerlist = []
super(EditRosterForm, self).__init__(*args, **kwargs)
currentroster = Roster.objects.filter(team=self.team)[0]
for member in Playerprofile.objects.filter(team=self.team).order_by('name'):
if member in currentroster.players.all():
self.fields[str(member.name)] = forms.ChoiceField(choices=ROSTER_CHOICES)
self.initial[str(member.name)] = '1'
elif member in currentroster.subs.all():
self.fields[str(member.name)] = forms.ChoiceField(choices=ROSTER_CHOICES)
self.initial[str(member.name)] = '2'
self.members += 1
def clean(self):
cleaned_data = super().clean()
i = 0
for member in Playerprofile.objects.filter(team=self.team):
if cleaned_data[member.name] == '1':
self.playerlist.append(member)
elif cleaned_data[member.name] == '2':
self.sublist.append(member)
i += 1
print(len(self.sublist))
if len(self.sublist) > 2:
raise ValidationError("Maximum of 2 subs allowed")
if len(self.playerlist) > 5:
raise ValidationError("Maximum of 5 players allowed")
if len(self.playerlist) + len(self.sublist) > i:
raise ValidationError("Team members must be a sub or a player")
return cleaned_data
def save(self):
cleaned_data = self.cleaned_data
print(cleaned_data)
UpdateRoster(roster=self.team.GetCurrentRoster(), players=self.playerlist, subs=self.sublist)
When my form has errors I get
The view team.views.TeamEditView didn't return an HttpResponse object. It returned None instead.
I know I need to add something to pass my form the form object with errors but can't find how to do this.
if edit_roster_form.is_valid():
edit_roster_form.save()
return redirect ('tcl-team', slug=self.request.user.playerprofile.team.urlslug)
else:
# Render detail view page with form
Apologies if my question is incoherent, I'm new to django and stackoverflow
I think you have to add request as parameter to the render shortcut
I am getting error Cannot assign "'1'": "dropdown.drp1" must be a "basedrop" instance. I am sharing my code. Kindly help. I got some solutions on stack but I did not understand how to implement that in my case. Django error. Cannot assign must be an instance
models.py
class basedrop(models.Model):
name = models.CharField(max_length=50,blank=False,null=False)
def __str__(self):
return self.name
class subdrop(models.Model):
name = models.CharField(max_length=100,blank=False,null=False)
bsdrop = models.ForeignKey(basedrop,null=False,blank=False,on_delete=models.CASCADE)
def __str__(self):
return self.name
class lastdrop(models.Model):
name = models.CharField(max_length=100,blank=False,null=False)
sbdrop = models.ForeignKey(subdrop,null=False,blank=False,on_delete=models.CASCADE)
def __str__(self):
return self.name
class dropdown(models.Model):
name = models.CharField(max_length=50)
drp1 = models.ForeignKey(basedrop,max_length=50,on_delete=models.CASCADE)
drp2 = models.ForeignKey(subdrop,max_length=50,on_delete=models.CASCADE)
drp3 = models.ForeignKey(lastdrop,max_length=50,on_delete=models.CASCADE)
def __str__(self):
return self.name
views.py
def create_drop(request):
if request.method == 'POST':
form = dropdownForm(request.POST or None)
if form.is_valid():
form = dropdown(name=request.POST.get('name'),drp1_Id=int(request.POST.get('drp1')),
drp2_Id=int(request.POST.get('drp2')),drp3_Id=int(request.POST.get('drp3')))
form.save()
return HttpResponse('<p>this is working</p>')
form = dropdownForm()
return render(request,'drop.html',{'form':form})
forms.py
class dropdownForm(forms.ModelForm):
drp1 = forms.ChoiceField(choices=((bs.get('id'),bs.get('name')) for bs in basedrop.objects.all().values('id','name')))
class Meta:
model = dropdown
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['drp2'].queryset = subdrop.objects.none()
self.fields['drp3'].queryset = lastdrop.objects.none()
if 'drp1' in self.data:
try:
country_id = int(self.data.get('drp1'))
self.fields['drp2'].queryset = subdrop.objects.filter(id=country_id).order_by('name')
except (ValueError, TypeError):
pass
elif 'drp2' in self.data:
try:
country_id = int(self.data.get('drp2'))
self.fields['drp3'].queryset = lastdrop.objects.filter(id=country_id).order_by('name')
except (ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['drp2'].queryset = self.instance.drp1.city_set.order_by('name')
self.fields['drp3'].queryset = self.instance.drp2.city_set.order_by('name')
I don't know if it could cause failures but you're passing the POSTed argument 'drp1' as integer for drp1_Id, drp2_Id and drp3_Id.
You'd have it much easier if you choose a more intuitive coding style.
For example this line:
form = dropdown(name=request.POST.get('name'), drp1_Id=int(request.POST.get('drp1')), drp2_Id=int(request.POST.get('drp1')), drp3_Id=int(request.POST.get('drp1')))
If you get the objects and pass them to the dropdown you gain readability specially if there is an error:
drp1_pk = request.POST.get('drp1')
drp1 = basedrop.objects.get(pk=drp1_pk)
drp2 = subdrop.objects.get(pk=drp1_pk)
drp3 = lastdrop.objects.get(pk=drp1_pk)
form = dropdown(name=request.POST.get('name'), drp1=drp1, drp2=drp2, drp3=drp3)
But again:
It looks strange to pass the same primary key to three different models.
The beginning is simple:
class Question(models.Model):
question_string = models.CharField(max_length=255)
answers = models.CharField(max_length=255)
answers are json of list of strings e.g ['Yes', 'No']. Number of answers is dynamic.
The challenge for me now is to write a form for this model.
Current state is:
class NewQuestionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(NewQuestionForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['answers'] = AnswerField(num_widgets=len(json.loads(self.instance.answers)))
class Meta:
model = Question
fields = ['question']
widgets = {
'question': forms.TextInput(attrs={'class': "form-control"})
}
class AnswerField(forms.MultiValueField):
def __init__(self, num_widgets, *args, **kwargs):
list_fields = []
list_widgets = []
for garb in range(0, num_widgets):
field = forms.CharField()
list_fields.append(field)
list_widgets.append(field.widget)
self.widget = AnswerWidget(widgets=list_widgets)
super(AnswerField, self).__init__(fields=list_fields, *args, **kwargs)
def compress(self, data_list):
return json.dumps(data_list)
class AnswerWidget(forms.MultiWidget):
def decompress(self, value):
return json.loads(value)
The problem is: i get 'the JSON object must be str, not 'NoneType'' in template with '{{ field }}'
What is wrong?
I found the problem. I forgot to add 'answers' to class Meta 'fields'.
So my example of dynamic Multiwidget created from Model is:
class NewQuestionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
# need this to create right number of fields from POST
edit_mode = False
if len(args) > 0:
edit_mode = True
answer_fields = 0
for counter in range(0, 20):
answer_key = "answers_" + str(counter)
if args[0].get(answer_key, None) is not None:
answer_fields = counter + 1
else:
break
super(NewQuestionForm, self).__init__(*args, **kwargs)
if edit_mode:
self.fields['answers'] = AnswerField(num_widgets=answer_fields, required=False)
# get number of fields from DB
elif 'instance' in kwargs:
self.fields['answers'] = AnswerField(num_widgets=len(json.loads(self.instance.answers)), required=False)
else:
self.fields['answers'] = AnswerField(num_widgets=1, required=False)
class Meta:
model = Question
fields = ['question', 'answers']
widgets = {
'question': forms.TextInput(attrs={'class': "form-control"})
}
def clean_answers(self):
temp_data = []
for tdata in json.loads(self.cleaned_data['answers']):
if tdata != '':
temp_data.append(tdata)
if not temp_data:
raise forms.ValidationError('Please provide at least 1 answer.')
return json.dumps(temp_data)
'clean_answers' has 2 porposes: 1. Remove empty answers. 2. I failed to set required attribute on first widget. So i check here at least 1 answer exists
class AnswerWidget(forms.MultiWidget):
def decompress(self, value):
if value:
return json.loads(value)
else:
return ['']
class AnswerField(forms.MultiValueField):
def __init__(self, num_widgets, *args, **kwargs):
list_fields = []
list_widgets = []
for loop_counter in range(0, num_widgets):
list_fields.append(forms.CharField())
list_widgets.append(forms.TextInput(attrs={'class': "form-control"}))
self.widget = AnswerWidget(widgets=list_widgets)
super(AnswerField, self).__init__(fields=list_fields, *args, **kwargs)
def compress(self, data_list):
return json.dumps(data_list)