2015-04-02 45 views
0

我正在使用django 1.4.5。我添加到模型中,選擇T恤衫的尺寸。模型中的字段在django應用程序中不發生變化

場在我的模型

tshirt_size = models.CharField(choices=TSHIRT_SIZE_CHOICES, default="s", blank=True, null=True, max_length=24) 

我的形式

class SubscriberForm(forms.ModelForm): 
    class Meta(): 
     model = Subscriber 
     exclude = ['event', 'is_active'] 
     widgets = { 
      'name': TextInput(), 
      'last_name': TextInput(), 
      'email': TextInput(), 
      'tshirt_size': Select(choices=TSHIRT_SIZE_CHOICES) 
     } 

考慮,我得到這樣的數據:

tshirt_size = request.POST.get('tshirt_size') 

HT的一部分毫升代碼

<label for="id_tshirt_size">T-Shirt Size (Unisex):</label> 
{{ form.tshirt_size }} 

當我執行保存的形式我在tshirt_size管理面板無價值得到。

+0

當你使用'ModelForm'時,爲什麼在你的視圖中查找'request.POST.get('tshirt_size')'?照顧它是形式的工作。看起來你沒有正確使用'ModelForm'。 – 2015-04-02 09:17:34

+0

如果我從我的視圖中刪除這部分:'tshirt_size = request.POST.get('tshirt_size')'我總是獲得大小「S」(默認)evan當我選擇「L」大小時,例如@brunodesthuilliers – mark 2015-04-02 09:30:07

+0

顯然不是以正確的方式使用你的形式。它是一個ModelForm,它知道如何從請求中獲取數據,驗證它們,並創建/更新模型實例。您__dont__必須在視圖代碼(您沒有發佈FWIW)中手動執行此操作,只需按照預期使用表單。 – 2015-04-02 10:35:13

回答

1

這裏使用的ModelForm創建或更新模型實例的正規途徑:

def myview(request, pk=None): 
    if pk: 
     instance = get_object_or_404(Subscriber, pk=pk) 
    else: 
     instance = None 
    if request.method == "POST": 
     form = SubscriberForm(request.POST, instance=instance) 
     if form.is_valid(): 
      instance = form.save() 
      # do whatever with instance or just ignore it 
      return redirect(some return url) 
    else: 
     form = SubscriberForm(instance=instance) 
    context = {"form":form} 
    return render(request, "path/to/your/template.html", context) 

如果您認爲看起來並不像它那麼你很可能就錯了。在你看來,你提到的tshirt_size = request.POST.get('tshirt_size')肯定是你做錯FWIW的味道。

+0

我有其他領域在我看來,這是收集在這種方式和工作。這裏是select和view是None。 – mark 2015-04-02 11:36:59

+0

@mark,因爲您沒有發佈所有相關代碼(模型的一行,視圖的一行,模板的兩行...),因此無法知道您的代碼中_else_錯誤。但實際上,從正確的方式開始使用Django,它會爲您節省時間,問題,安全問題和頭痛。 – 2015-04-02 13:28:42