How to get currently selected choice from CharField in Django? - django

I'm trying to get the currently selected choice from the CharField and use it in str method like this:
class Foo(models.Model):
measurement_value = models.FloatField(max_length=200)
CHOICES = (('a', 'Alpha'), ('b', 'Beta'))
choice = models.CharField(max_length=5, choices=CHOICES, default='a')
def __str__(self):
"""String representation for the foo object."""
return str(self.measurement_value) + " " + self.choice
So for example, if I'd like to add object foo with measurement 10.5 and choice 'a' (Alpha), str would return this: "10.5 Alpha"
Currently, the code that I provided returns this: "10.5 a".

You can get the human readable choice name by using instance method get_{}_display
your example
def __str__(self):
return str(self.measurement_value) + " " + self.get_choices_display()

Related

Django form Data

Please I gotta a model I created with three fields input1,input2,total. So I generated a model form so that if I input the values of input 1 and input2 it will automatically multiply the the inputted values. Then on calling the save method it will save the inputted values and computed value to the database
Try this:
class Multiply(models.Model):
input1 = models.IntegerField()
input2 = models.IntegerField()
result = models.IntegerField(null=True, blank=True)
def __str__(self):
return str(self.input1) + " * " + str(self.input2) + " = " + str(self.result)
def save(self, *args, **kwargs):
self.result = self.input1 * self.input2
super().save(*args, **kwargs)

how to access to property in view(django)

I'm beginner and I need some solution
First, I have Racket and Detail class.
class Racket(models.Model):
name = models.CharField(max_length=20)
class RacketDetail(models.Model):
racket = models.OneToOneField(Racket, related_name='detail', on_delete=models.CASCADE)
adminReview = models.TextField()
adminPower = models.FloatField(default=0)
adminSpin = models.FloatField(default=0)
adminManeuverability = models.FloatField(default=0)
adminStability = models.FloatField(default=0)
adminComfort = models.FloatField(default=0)
#property
def adminAvgScore(self):
scoreAvg = (
self.adminPower +
self.adminSpin +
self.adminManeuverability +
self.adminStability +
self.adminComfort
) / 5
return round(scoreAvg, 2)
Second, I want to rander list using the #property(adminAvgScore), so I made view like this.
def racketMain(request: HttpRequest):
getRacket = Racket.objects.all().order_by('detail__adminAvgScore')
return render(request, "racket/racketMain.html", {'racketItems': getRacket, })
Unfortunally when I use 'RacketDetail' class's column I can access all column except 'adminAvgScore' using by "order_by('detail__".
If I use like "order_by('detail__adminAvgScore')" then Django show to me error "Unsupported lookup 'adminAvgScore' for BigAutoField or join on the field not permitted."
How can I solve it? Or should I think in a different way?
You cannot use property with Query as Property is Function. You can use annotate and aggregate combination to get the result as your property function but inside a query.Something like this will do the trick.
from django.db.models import F, Sum, FloatField, Avg
Model.objects.filter(...)\
.values('id')\
.annotate(subtotal=Sum(...math here..., output_field=FloatField()))\
.aggregate(total=Avg(F('subtotal')))

django modelchoicefield select columns

I can't figure out how to format the output of a ModelChoiceField when only 2 or 3 columns are selected.
Here is my model:
class ActsIdsModel(models.Model):
releveAnnee = models.IntegerField(max_length=4, blank=False, null=False)
releveMois=models.IntegerField(max_length=2, blank=False, null=False)
noOrdre=models.IntegerField(max_length=2, blank=False, null=False)
...
#many other fields
...
def __unicode__(self):
releveAnnee=vn.variablesNameDic['releveAnnee'] + "=" + str(self.releveAnnee)
releveMois=vn.variablesNameDic['releveMois'] + "=" + str(self.releveMois)
noOrdre=vn.variablesNameDic['noOrdre'] + "=" + str(self.noOrdre)
return releveAnnee + ", " + releveMois + ", " + noOrdre
The code below works but I get all the columns (so not efficient for my purpose):
class ActsAddForm(forms.Form):
actsToValidate=forms.ModelChoiceField(queryset=ActsIdsModel.objects.filter(validated=0))
But the code below does not work:
class ActsAddForm(forms.Form):
actsToValidate=forms.ModelChoiceField(queryset=ActsIdsModel.objects.values("releveAnnee", "releveMois", "noOrdre").filter(validated=0))
How to fix the problem? It seems that when I choose the columns the unicode function of my model is not called anymore. Right?
Use .only() method instead of .values():
https://docs.djangoproject.com/en/1.5/ref/models/querysets/#django.db.models.query.QuerySet.only

Using Django Forms: How can i use the chosen value of a forms.ModelChoiceField within a userdef validation

I got the following model:
class currency(models.Model):
currency = models.CharField(max_length=50)
dollaramount = models.DecimalField(max_digits=10, decimal_places=2)
def __unicode__(self):
return self.currency
This Model contains 2 entrys with currency-value "$" and "€"
The currency-model is related with a ModelChoiceField within the following form, which has a userdefined validation "clean_amount" for checking the amount, depending which currency is actual choosen in the currencyfield from the from itself.
How can i do the compare inside the userdef-validation "clean_amount", if the value from the selected object is "$" or "€"?
from django import forms
from currencies.models import currency
class createform(forms.Form):
currency = forms.ModelChoiceField(queryset = currency.objects.all())
amount = forms.DecimalField(initial = 0)
def clean_amount(self):
currencyfield = self.cleaned_data['currency']
amount = self.cleaned_data['amount']
if amount < 0:
raise forms.ValidationError("Amount must be at least 0.")
#HERE I WANT TO CHECK
choosencurrency = currencyfield.??????
if choosencurrency == "$" :
#check $amount
if choosencurrency == "€" :
#check €amount
return amount
You should do this in clean(), not clean_amount(). From clean you can access self.cleaned_data['amount'] and self.cleaned_data['currency'].

Django model field relating to a few models

Imagine a 5x5 grid (map), every field of it represents a certain object (it can be a monster, a tree etc.)
So, here we have:
class Field(Model):
x = y = PositiveIntegerField()
content = ...(?)
Here the problem arises. Here is the alternative, but I think this way is too messy, especially if I have many different content ids.
class Field(Model):
x = y = PositiveIntegerField()
content = PositiveIntegerField()
monster_rel = ForeignKey(Monster, null=True, blank=True)
building_rel = ForeignKey(Monster, null=True, blank=True)
nature_obj_rel = ForeignKey(Monster, null=True, blank=True)
and then in a view:
f = Field.objects.get(pk=1)
if f.content == 1:
print "Monster %s of level %d" % (f.monster_rel.name, f.monster_rel.level)
elif f.content == 2:
print "This is a %s" % f.building_rel.type
...
Is there a better solution for this?
EDIT
I would like fields like:
content_id = IntegerField()
content_rel = FieldRelatedToModelByContentId()
Well, sounds like generic relations is exactly what you're looking for.