亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Django 使用模型形式更新模型實例

Django 使用模型形式更新模型實例

三國紛爭 2023-04-25 15:59:50
我在 Django 中有以下模型,用于存儲有關藥物的數據。class Medicine(models.Model):    Medicine_Name = models.CharField(max_length=100)    User_Associated = models.ForeignKey(User, on_delete=models.CASCADE)    Tablets_In_Box = models.IntegerField()    Dose_in_mg = models.IntegerField()    Dose_Tablets = models.IntegerField()    Number_Of_Boxes = models.IntegerField()    Last_Collected = models.DateField()    def __str__(self):        return self.Medicine_Name        def get_absolute_url(self):        return reverse('tracker-home')我正在嘗試創建一個模型表單,用戶可以在其中更新他們的一種藥物的最后一個集合。這是我開始的。class CollectionForm(forms.ModelForm):    class Meta:        model = Medicine        fields = ['Medicine_Name', 'Number_Of_Boxes', 'Last_Collected']我不明白如何根據現場的“Medicine_Name”調用我的模型實例。換句話說,我需要用戶能夠從下拉菜單中選擇正確的藥物,然后表單必須更新我的藥物模型上的“Last_Collected”和“Numer_Of_Boxes”字段。https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#the-save-method這似乎包含相關信息,但我很難了解如何在這種情況下使用它。如何根據表單中的用戶輸入正確獲取我需要的藥物表單實例?此外,如何在我的視圖中使用 save 方法來確保數據庫得到正確更新?編輯為表單添加了視圖:def update(request, pk):        instance = Medicine.objects.get(id=pk)    if request.method == 'POST':        form = CollectionForm(user=request.user, instance=instance, data=request.POST)                if form.is_valid():            instance = form.save(commit=False)            instance.User_Associated = request.user            instance.save()    else:        form = CollectionForm()     context = {'form': form}    return render(request, 'tracker/medicine_collection.html', context )
查看完整描述

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 ('/')

        ....


查看完整回答
反對 回復 2023-04-25
?
慕田峪7331174

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 鏈接到上面的示例并自己嘗試一些事情。


查看完整回答
反對 回復 2023-04-25
?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

這是基于更新特定用戶的實例。本教程幫助我實現了同樣的目標。

https://youtu.be/EX6Tt-ZW0so


查看完整回答
反對 回復 2023-04-25
  • 2 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號