coddingtonbear / django-measurement

Easily store, retrieve, and convert measurements of weight, volume, distance, area and more.
MIT License
145 stars 33 forks source link

Customizing the form unit choices #103

Closed jimmybutton closed 3 years ago

jimmybutton commented 3 years ago

Thanks for this project, it seems to be really useful! I've spend some time trying to get started with it. I managed to create a form and render it in a template like this:

# models.py
from django.db import models
from django_measurement.models import MeasurementField
from measurement.measures import Volume

class Entry(models.Model):
    name = models.CharField(max_length=255, verbose_name='Beverage')
    volume = MeasurementField(measurement=Volume)

# forms.py
from django import forms
from .models import Entry

class EntryForm(forms.ModelForm):

    class Meta:
        model = Entry
        fields = ["name", "volume"]

I was trying to modify the units displayed in the dropdown like shown in the documentation:

# forms.py
from measurement.measures import Volume
from django_measurement.models import MeasurementField

class BeerForm(forms.Form):

    volume = MeasurementField(
        measurement=Volume,
        unit_choices=(("l","l"), ("oz","oz")),
    )

However when playing with this form in the django shell, it seems there are no fields:

from entries.forms import BeerForm
b = BeerForm()
b.fields
>> {}
b.as_table()
>> ''

I tried different things, using MeasurementWidget or modifying the widget via the widget property in the Meta class in the ModelForm approach.

Am I missing something here? Any advice welcome, thanks!

django = "~=3.1.0" django-measurement = "==3.2.3" python_version = "3.8"

codingjoe commented 3 years ago

Hi @jimmybutton thanks for reaching out. I think the solution to your problem might be rather simple. You are using the MeasurementField from models not forms. Of course a model field won't work in a form and vice versa. Small typo I guess, happens to the best of us ;) Let me know if you have any other questions. Best Joe

jimmybutton commented 3 years ago

Hi @codingjoe many thanks, that solved it!

Maybe someone else will find this useful: It is also possible to define the unit_choices on the Model itself. They then get passed through when using a ModelForm - great stuff!