Display forms choice in template-Django - django

On the template, when I call person.health_issue, I am getting '1','2' instead of 'Abdominal pain','Anaphylaxis'. How to display the value ('Abdominal pain','Anaphylaxis') instead of the code(1 or2 etc).
I tried with this also {{ person.get_health_issue_display }} in template,it is not displayed anything.
forms.py
HEALTH_USSUES = (
('1', 'Abdominal pain'), ('2', 'Anaphylaxis'), ('3', 'Asthma'),
('4', 'Bruising'), ('5', 'Chest pains'), ('6', 'Coughs or Colds')
)
class PersonActionsForm(forms.ModelForm):
action = forms.MultipleChoiceField(widget=forms.Select(), choices=HEALTH_USSUES, required=False)
models.py
class ReportPerson(models.Model):
report = models.ForeignKey(Report)
name = models.CharField('Name', max_length=100)
first_aid = models.BooleanField('First aid', default=False)
health_issue = models.IntegerField(default=0)
views.py
def report_template(request):
""""""
person = ReportPerson.objects.get(pk=person_id)
""""""
return render(request, 'event/print.html',
{
'person':person
})
can any one tell me how to do this.
Thanks

As you don't have any choices set in model field health_issue you need to write the get_health_issue_display method by your self i will name it as health_issue_display so that default get_FOO_display method not gets overridden:
HEALTH_USSUES = (
(1, 'Abdominal pain'), (2, 'Anaphylaxis'), (3, 'Asthma'),
(4, 'Bruising'), (5, 'Chest pains'), (6, 'Coughs or Colds')
)
class ReportPerson(models.Model):
report = models.ForeignKey(Report)
name = models.CharField('Name', max_length=100)
first_aid = models.BooleanField('First aid', default=False)
health_issue = models.IntegerField(default=1)
def health_issue_display(self):
for c in HEALTH_USSUES:
if c[0] == self.health_issue:
return c[1]
Or just add choices in the model field:
health_issue = models.IntegerField(default=1, choices=HEALTH_USSUES)
Now you have get_health_issue_display.
Also make the first value in every choice as integer (1, 'Abdominal pain') rather than string '1'. Just to remove the confusion.
You have default=0 which does not exists in choices. Change it to default=1

Related

How can I calculate avg of data from django form and store in variable for later use?

In the readerpage function, in my views.py, I am trying to calculate the avg of the two variables: readability_rating and actionability_rating, and store the result in avg_rating
def readerpage(request, content_id):
content = get_object_or_404(Content, pk=content_id)
form = ReviewForm(request.POST)
if form.is_valid():
review = form.save(commit=False)
review.content = content
readability_rating = form.cleaned_data['readability_rating']
readability = form.cleaned_data['readability']
actionability_rating = form.cleaned_data['actionability_rating']
actionability = form.cleaned_data['actionability']
general_comments = form.cleaned_data['general_comments']
review.avg_rating = (float(readability_rating) +
float(actionability_rating)) / 2
review.save()
return redirect('home')
args = {'content': content, 'form': form}
return render(request, 'content/readerpage.html', args)
The problem is that with this setup the two variables are still ChoiceFields - as such the above setup gives me the error:
float() argument must be a string or a number, not 'ChoiceField'
I’ve tried converting them to floats without any luck.
I also attempted using the TypedChoiceField with coerce=float, still with no luck
I’m not sure whether the best place to calculate this is in my function, my form, or my model?
models.py:
class Review(models.Model):
content = models.ForeignKey(Content, null=True, on_delete=models.CASCADE)
readability = models.CharField(null=True, max_length=500)
readability_rating = models.IntegerField(null=True)
actionability = models.CharField(null=True, max_length=500)
actionability_rating = models.IntegerField(null=True)
general_comments = models.CharField(null=True, max_length=500)
avg_rating = models.FloatField(null=True)
def _str_(self):
return self.title
forms.py:
class ReviewForm(forms.ModelForm):
readability = forms.CharField(widget=forms.Textarea)
readability_rating = forms.ChoiceField(
choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])
actionability = forms.CharField(widget=forms.Textarea)
actionability_rating = forms.ChoiceField(
choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])
general_comments = forms.CharField(widget=forms.Textarea)
class Meta:
model = Review
fields = ['readability', 'readability_rating',
'actionability', 'actionability_rating', 'general_comments']
Thanks for reading this.
The variables are ChoiceFields because you are declaring them as ChoiceFields in view function. Shouldn't you just fetch the values from your cleaned_data?
readability_rating = form.cleaned_data['readability_rating']
And to the second part of your question: Why not add it as a #property to your model?

how to limit_choices_to self field id in django model

how use limit_choices_to in django
class Category(models.Model):
"""
商品类别
"""
CATEGORY_TYPE = (
(1, "一级类目"),
(2, "二级类目"),
(3, "三级类目"),
)
def limit_category_type_choice(self):
obj = Category.objects.get(category_type=self.category_type)
field_object = Category._meta.get_field('category_type')
field_value = field_object.value_from_object(obj)
return {'category_type__lte': field_value}
category_id = models.AutoField(primary_key=True, verbose_name='category_id')
category_title = models.CharField(default='', max_length=50, verbose_name='目录标题', help_text='目录标题')
category_name = models.ForeignKey(LinkDesignate,blank=True, null=True, to_field='link_des_text_id', related_name='category', on_delete=models.CASCADE)
category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="类目级别", help_text="类目级别")
parent_category = models.ForeignKey("self", limit_choices_to=self.limit_category_type_choice, null=True, blank=True, verbose_name="父类目级别", help_text="父目录",
related_name="sub_cat", on_delete=models.CASCADE)
class Meta:
verbose_name = "产品目录"
verbose_name_plural = verbose_name
i know this
limit_choices_to=self.limit_category_type_choice,
this is wrong , because name 'self' is not defined
how can to use the function limit_category_type_choice
the document is:
def limit_pub_date_choices():
return {'pub_date__lte': datetime.date.utcnow()}
limit_choices_to = limit_pub_date_choices
how can i change my Function limit_category_type_choice without self
but can use the self instance
Put the def out of the class ;-)
This was my solution, it is similar.
It limits the films which can be choosen for an event.
Films with status '2' in class Film over ForeignKey OR
over reverse ForeignKey: Films with an Event with date in the future
the model:
def limit_film_choices():
date = str(datetime.datetime.now())
result = Q( status = '2') | Q( event_film__date__gte = date)
return result
class Film(models.Model):
STATUS_COICES = [
('1' , 'a'),
('2' , 'b'),
]
status = models.CharField( max_length=16, choices=STATUS_COICES, default='1')
class Event(models.Model):
film = models.ForeignKey('filme.Film', on_delete=models.CASCADE, related_query_name='event_film',
related_name='event_film', blank = True, null=True, limit_choices_to = limit_film_choices)
date = models.DateTimeField(auto_now=False, null=True)

get long name during annotate in django ORM query

I have this model:
class Rank(models.Model):
RANK_TYPE_CHOICES = (
('O', 'Officer'),
('E', 'Enlisted'),
('V', 'Civilian'),
('C', 'Cadet'),
)
ShortName = models.CharField(max_length=50)
LongName = models.CharField(max_length=500)
Type = models.CharField(max_length=1, choices=RANK_TYPE_CHOICES, default='O')
Genre = models.ForeignKey(Genre, on_delete=models.DO_NOTHING)
Career = models.ForeignKey(Career, on_delete=models.DO_NOTHING)
image = models.ForeignKey(Photos, on_delete=models.DO_NOTHING)
when I perform this ORM action:
models.Rank.objects.values('Type').annotate(total=Count('Type')).order_by()
I get this response
<QuerySet [{'Type': 'O', 'total': 1}]>
Exactly as I want.
However, as you can see, it gives me the short type. How do I make it show the long name instead of the type choice short name?
Thanks.
You will need to add the values manually.
rank_dict = dict(RANK_TYPE_CHOICES)
for obj in my_ranks:
obj['full_type'] = rank_dict[obj['Type']]

get all rows that foreignkey exist on other table by id filtered by employeeid

I'have the following ORM Query set, it works properly but now i need it to exclude itself from appearing to a user who already added a row with the same id on the table.
In other words i want the user not to answer the question twice if the user already added an answer to that specific question he will never see the values. here is my query ORM
right_now = datetime.datetime.now() - timedelta(minutes=-10)
partidos = encuesta.objects.filter(fecha__gt=right_now).order_by('fecha')
this ORM Query above shows all the Questions from today untill 10 minutes before the due date.
Now i want show only the questions that a specific user has already answered. as you can see below, i need only to appear those questions he has not answered yet but still being filtered by the date and same order.
Any ideas?
Here is my model.
models.py
class equipo(models.Model):
nombre = models.CharField(max_length=30)
bandera = StdImageField(upload_to='bandera/%Y/%m/%d',
variations={
'large':(53,53, False),
'thumbnail': (70, 26, False)})
GRUPOS = (
('A', 'Grupo A'),
('B', 'Grupo B'),
('C', 'Gropo C'),
('D', 'Gropo D'),
('E', 'Gropo E'),
('F', 'Gropo F'),
('G', 'Gropo G'),
('H', 'Gropo H'),
)
grupo = models.CharField(max_length=1, choices=GRUPOS)
def banderaEquipo(self):
return '<img src="/media/%s">' % (self.bandera.thumbnail)
banderaEquipo.allow_tags = True
def __unicode__(self):
return self.nombre
class encuesta(models.Model):
equipoA = models.ForeignKey(equipo, related_name='equipo_equipoA')
golesEquipoA = models.IntegerField(max_length=2, null=True, blank=True)
equipoB = models.ForeignKey(equipo, related_name='equipo_equipoB')
golesEquipoB = models.IntegerField(max_length=2, null=True, blank=True)
ETAPA = (
('1', 'Primera Etapa'),
('2', 'Octavos De Final'),
('3', 'Cuartos De Final'),
('4', 'Semifinal'),
('5', 'Final'),
('6', '3ra Posicion')
)
etapa = models.CharField(max_length=1, choices=ETAPA)
fecha = models.DateTimeField(auto_now_add=False)
def __unicode__(self):
return "%s Vs. %s" % (unicode(self.equipoA), unicode(self.equipoB))
class respuesta(models.Model):
encuesta = models.ForeignKey(encuesta)
empresa = models.ForeignKey(empresa)
empleado = models.ForeignKey(empleado)
equipoA = models.IntegerField(max_length=1)
equipoB = models.IntegerField(max_length=1)
fecha = models.DateField(auto_now_add=True)
def __unicode__(self):
return "%s" % (unicode(self.encuesta))
Main idea:
Question.objects.exclude(answers__user=user)
In your case (if you add related_name encuestas to respuesta FK field encuesta):
encuesta.objects.exclude(respuesta__empleado=user).filter(fecha__gt=right_now).order_by('fecha')

Value of a field by default Django Admin

I have the following model
class Trivias(models.Model):
GIFT_CHOICES = (
('gas', 'Gasolina'),
('money', 'Dinero'),
('xp','Experiencia'),
)
NUMQ_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
idtrivias = models.IntegerField(primary_key=True)
url = models.CharField(max_length=450)
numQ = models.IntegerField(max_length=4,choices=NUMQ_CHOICES)
idtipospropiedades = models.ForeignKey(Tipospropiedades, db_column='idtipospropiedades')
idtitulos = models.ForeignKey(Titulos, db_column='idtitulos')
correct = models.IntegerField(max_length=1)
gift = models.CharField(max_length=5,choices=GIFT_CHOICES)
value = models.CharField(max_length=20)
class Meta:
db_table = u'trivias'
I want the url field has a default value in the Django Admin, How I can do?
regards
Is there any reason you're storing the URL as a CharField rather than a URLField? URLField is a URL-specific subclass of CharField. Also, to set default values, use default="x", e.g.
url = models.URLField(default='http://www.foo.com')
Hope that helps.