Django:如何自定义表单ChoiceField显示?

时间:2015-10-23 08:30:25

标签: python django django-forms

我正在用Django创建一个极简主义商店。

class CardOrderForm(forms.Form):
    order = forms.ChoiceField(
        label="",
        choices=ORDER_CHOICES,
        widget=forms.RadioSelect)

ORDER_CHOICES = (
    ('CARDS_100_G', 'Pack de 100 cartes génériques'),
    ('CARDS_200_G', 'Pack de 200 cartes génériques'),
    ('CARDS_500_G', 'Pack de 500 cartes génériques'))

然后,我创建了一个对象来将价格映射到订单选择:

ORDER_PRICES = {
    # Without/With TAXES
    'CARDS_100_G': (39, 46.80),
    'CARDS_200_G': (69, 82.80),
    'CARDS_500_G': (149, 178.80))}

目前,在我的模板中,我有{{ form.order }},其中显示了3个选项的原始列表,如下所示:

  • Pack de 100cartesgénériques
  • Pack de 200cartesgénériques
  • Pack de 500cartesgénériques

但是,我无法找到一种方法来自定义此显示,以便能够在项目旁边添加价格。我想得到这个结果:

  • Pack de 100cartesgénériques - 39€
  • Pack de 200cartesgénériques - 69€
  • Pack de 500cartesgénériques - 149€

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:1)

您可以动态创建一组新选项。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Employee
{
private:
    string firstName;
    string lastName;
public:
    void setLastname(string);
    void setFirstname(string);
    string getLastname() const{return lastName;}
    string getFirstname() const{return firstName;}

    //create a constructor
    Employee(string firstName, string lastName)
        : firstName(firstName), lastName(lastName)
    {}
};

int main()
{
    vector<Employee> emp;
    int count = 0;
    cout << "Enter the amount of employees to add:" << endl;
    cin >> count;

    string firstName, lastName;
    for(int i = 0; i < count; ++i)
    {
        cout << "Please enter the first and last names" << endl;

        cin >> firstName;
        cin >> lastName;

        emp.emplace_back(firstName, lastName);
    }

    for(const Employee & e : emp)
    {
        cout << "Employee:" << endl;
        cout << e.getFirstname() << " " << e.getLastname() << endl;
    }
}