2016-06-16 41 views
1

我正在學習Django,我需要允許應用的用戶能夠通過模板向item_name字段添加更多選項,但是我沒有任何想法關於如何實現這一點。謝謝您的幫助。如何通過模板在django模型選擇中添加選項

這裏是我的模型

class ItStore(models.Model): 
    type_choice = (
      ('Printer Catridge', 'Printer Catridge'), 
      ('UPS', 'UPS'), 
      ('UPS Battery', 'UPS Battery'), 
      ('Mouse', 'Mouse'), 
      ('Keyboard', 'Keyboard'), 
     ) 
    item_name = models.CharField(max_length='100', blank=True, null=False, choices=type_choice) 
    quantity = models.IntegerField(default='', blank=True, null=False) 

這是我的看法

def itstore_create(request): 
    form = ItStoreCreateForm(request.POST or None) 
    submit = "Create IT Store Items" 
    if form.is_valid(): 
     instance = form.save(commit=False) 
     instance.save() 
     message = instance.item_name + " Successfully Created" 
     messages.success(request, message) 
     return redirect("items:itstore_list") 
    context = { 
     "form": form, 
     "title": "CREATE ITEM", 
    } 
    return render(request, "store_form.html", context) 

這裏是我的形式

class ItStoreCreateForm(forms.ModelForm): 
    class Meta: 
     model = ItStore 
     fields = ['item_name', 'quantity'] 
+0

有什麼額外的選項基於?換句話說,您何時添加其他選項? –

+0

如果用戶想要選擇不在當前選擇列表中的項目,則可以添加其他字段 – simplyvic

+0

然後,您不應該使用相同的下拉列表。 'item_name'上的'choices'是在表單初始化的時候設置的,所以任何不在'type_choice'中的新選項會給你'選擇一個有效的選擇。該選擇不是可用選擇之一錯誤。 –

回答

1

你可以ñ請在您的模型上定義choices=。但相反,請在模型外定義一個默認選項列表。

my_choices = (
    "foo", 
    "bar", 
    "pop", 
) 
class MyModel(models.Model): 
    my_field = models.CharField(max_length=100) 

然後在你看來,你會想導入的元組,並把它傳遞給你的模板:

from my_app.models import my_choices 

def my_view(request, *a, **kw): 
    # view logic 
    return render(request, "path/to/my/template", choices=my_choices) 

然後在你的模板,你可以有默認的選擇和字符串值選擇框。並且還有一個可選的input type=text,如果填充,它將保存到該字段。

喜歡的東西:

<select name="my_field"> 
<option value="" selected="selected">-----</option> 
{% for choice in choices %} 
    <option value="{{ choice }}">{{ choice }}</option> 
{% endfor %} 
</select> 

會給你默認選項。然後添加一個具有相同名稱的輸入,這將作爲可選的新選項。

<input type="text" name="my_field"/> 

(可選)您可以編寫JavaScript邏輯,以確保只有選擇框或文本字段被提交。

+0

「您無法在模型上定義選項=」。這基本上是我的想法。如果'選擇'被移到它自己的DB類中,那麼添加/刪除變得非常簡單。您可能想要發揮一定程度的節制,但這完全是另一回事。 –

+0

marcusshep,我是django的新手,我並不真正瞭解你在說什麼。你能用代碼舉例說明嗎?謝謝 – simplyvic

+0

我更新了我的答案 – marcusshep