2 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
觀點(diǎn):
def update(request, pk):
instance = Medicine.objects.get(id=pk)
if request.method == 'POST':
form = CollectionForm(instance=instance, data=request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.User_Associated = request.user
instance.save()
return redirect ('/')
....

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
嘗試了一種不同的方法(基于類的視圖 - UpdateView)我剛剛在 SO 上學(xué)到了這里。沒有測試它,但我認(rèn)為它是朝著正確方向邁出的一步。
class UpdateMedicine(LoginRequiredMixin, UpdateView):
? ? model = Medicine? #call the model you need to update
? ? fields = ['Medicine_Name', 'Number_Of_Boxes', 'Last_Collected'] #specify the fields you need to update
? ? template_name_suffix = 'medicine_update_form' #specify the template where the update form is living
? ? def get_context_data(self, **kwargs):
? ? ? ? context = super().get_context_data(**kwargs)
? ? ? ? context.update(
? ? ? ? ? ? user=self.request.user, #get the current logged in user
? ? ? ? ? ? instance=get_object_or_404(Medicine, pk=self.kwargs['pk']) #get the pk of the instance
? ? ? ? )
? ? ? ? return context
? ? def form_valid(self, form):
? ? ? ? form.instance.medicine = get_object_or_404(Medicine, slug=self.kwargs['pk'])
? ? ? ? return super().form_valid(form) #saves the updates to the instance?
? ? def get_success_url(self):
? ? ? ? return reverse('medicine-collection') #name of the url where your 'tracker/medicine_collection.html is living
將適當(dāng)?shù)哪0搴?url 鏈接到上面的示例并自己嘗試一些事情。

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
添加回答
舉報(bào)