简体   繁体   English

将外键值传递给Django中的Choice

[英]Passing foreign key value to Choice in Django

I'm a bit confused on how Forms and ModelForms work, I want to create colored buttons based on a field value while creating a form. 我对Forms和ModelForms的工作方式有些困惑,我想在创建表单时根据字段值创建彩色按钮。

{% for category in form.category  %}
<label class="colored-icon btn btn-default btn-sm" style="background-color: {{ category.color }}">
    {{ category.choice_label|slice:"1" }}
    {{ category.tag }}
</label>
{% endfor %}

The problem is that category.color obviously doesn't have value I need. 问题是category.color显然没有我需要的价值。

My form is based on a "Transaction" model. 我的表单基于“交易”模型。 I need to somehow access "color" attribute from "Category" model, which looks like this: 我需要以某种方式从“类别”模型访问“颜色”属性,如下所示:

forms.py

class TransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction

models.py

class Transaction(models.Model):
    category = models.ForeignKey(Category, default='Unspecified')

class Category(models.Model):
    color = models.CharField(max_length=10)

views.py

def index(request):
    form = TransactionForm(request.POST)
    new_transaction = form.save()
    context = {
        'form': form,
    }

return render(request, 'index.html', context)

What's the proper way to select and pass "category.color" to each field I'm creating? 选择“ category.color”并将其传递给我正在创建的每个字段的正确方法是什么?

Thanks. 谢谢。

Try this: 尝试这个:

class Category(models.Model):
    color = models.CharField(max_length=10)

    def __unicode__(self):
        return '%s - %s' % (self.OtherFieldName, self.color)

that way inside the select should look like this 选择内部的方式应如下所示

<option value='CategoryID'>OtherFieldName_value - color_value</option>

Alright, I've figured out a way to do so with modified @warath-coder answer. 好了,我想出了一种方法来修改@ warath-coder答案。 I wasn't able to access "_value" property if it was a way to go, so I had to implement "split" filter and use it to split value I've got and use "color" part of this value. 如果我无法访问“ _value”属性,那么我必须实现“ split”过滤器,并使用它来拆分获得的值,并使用该值的“ color”部分。

models.py

class Category(models.Model):
    color = models.CharField(max_length=10)

    def __unicode__(self):
        return '%s - %s' % (self.OtherFieldName, self.color)

split_filter.py

@register.filter(name='split')
def split(value, arg):
    return value.split(arg)

index.html

{% with category.choice_label|split:"-" as label %}
<label class="btn btn-default btn-sm" style="background-color: {{ label.1 }}">
  {{ label.0 }}
  {{ category.tag }}
</label>
{% endwith %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM