2 回答

TA貢獻1779條經驗 獲得超6個贊
觀點:
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貢獻1828條經驗 獲得超13個贊
嘗試了一種不同的方法(基于類的視圖 - UpdateView)我剛剛在 SO 上學到了這里。沒有測試它,但我認為它是朝著正確方向邁出的一步。
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
將適當的模板和 url 鏈接到上面的示例并自己嘗試一些事情。
添加回答
舉報