2 回答

TA貢獻1801條經驗 獲得超16個贊
我的問題是我沒有區分UpdateView類中的“GET”和“POST”調用,我試圖在post()方法中做所有事情。我花了一段時間才弄清楚,但現在我認為這很清楚。我最初使用get()方法,但我意識到get_context_data()更適合,因為它會自動加載大部分上下文(例如實例和表單),而不必在get()方法中從頭開始做所有事情.
在這里瀏覽 UpdateView 類的代碼,似乎還需要將 ModelFormMixin 添加到PartUpdate類的聲明中,以便get_context_data()方法自動加載與目標模型/實例關聯的表單(否則它看起來不會不要這樣做)。
這是我更新的views.py代碼:
class PartUpdate(UpdateView, ModelFormMixin):
model = PhysicalPart
template_name = 'part_update.html'
form_class = PartForm
success_url = reverse_lazy('part-list')
def get_context_data(self, **kwargs):
# Load context from GET request
context = super(PartUpdate, self).get_context_data(**kwargs)
# Get id from PhysicalPart instance
context['part_id'] = self.object.id
# Get category from PhysicalPart instance
context['part_category'] = self.object.category
# Add choices to form 'subcategory' field
context['form'].fields['subcategory'].choices = SubcategoryFilter[self.object.category]
# Return context to be used in form view
return context
def post(self, request, *args, **kwargs):
# Get instance of PhysicalPart
self.object = self.get_object()
# Load form
form = self.get_form()
# Add choices to form 'subcategory' field
form.fields['subcategory'].choices = SubcategoryFilter[self.object.category]
# Check if form is valid and save PhysicalPart instance
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)

TA貢獻1806條經驗 獲得超5個贊
據我了解,您正在嘗試編輯實例。這就是您在 Django 中的操作方式,它應該使用正確的值自動填充您的輸入:
my_record = MyModel.objects.get(id=XXX) form = MyModelForm(instance=my_record)
有關此答案的更多詳細信息:如何使用 django 表單編輯模型數據
如果您的模型正確完成(使用關系),則不需要為 Select 提供選項。
添加回答
舉報