我正在嘗試使用 modelchoicewidget 創建一個模型表單,該表單從另一個模型而不是模型表單所連接的模型繼承其選擇,并且該選擇將由當前登錄的用戶過濾。下面的示例說明了我的意圖 - 假設我有兩個不同的模型,其中一個模型允許用戶注冊膳食型別(早餐、晚餐等),另一個模型允許用戶根據這些膳食型別創建特定膳食,連接變數是膳食型別的標題。
模型.py:
class Mealtypes(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200, default='')
description = models.TextField(default='')
class Specificmeals(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
meal_name = models.CharField(max_length=200, default='')
mealtype = models.CharField(max_length=200, default='')
fruit = models.BooleanField(default=False)
meat = models.BooleanField(default=False)
dairy = models.BooleanField(default=False)
表格.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Mealtypes, Specificmeals
class MealAdder(ModelForm):
class Meta:
model = Specificmeals
fields = [
'meal_name',
'mealtype',
'fruit',
'meat',
'dairy',
]
widgets = {
'text': forms.Textarea(attrs={"style": "height:10em;" "width:60em;"}),
'mealtype': forms.ModelChoiceField(queryset=Mealtypes.title.filter(author='author')),
'fruit': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}),
'meat': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}),
'dairy': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}),
}
我正在嘗試使用 ModelChoiceField 使其從當前用戶過濾的 Mealtypes 模型中查詢膳食型別,但我不斷收到屬性錯誤(物件沒有屬性..)
我做錯了什么,我該如何解決?
uj5u.com熱心網友回復:
首先,將以下內容添加到您的Mealtype模型中,以便您可以輸出 MealType 的實際標題:
def __str__(self):
return f"{self.title}"
然后,首先在您的視圖中傳遞請求用戶:
form = MealAdder(author=request.user)
然后在您forms.py的表單中,您應該使用__init__如下所示的查詢集:
from django.forms import TextInput, CheckboxInput, Select, ModelChoiceField
class MealAdder(ModelForm):
def __init__(self, author, *args, **kwargs):
super(MealAdder, self).__init__(*args, **kwargs)
self.fields['mealtype'] = forms.ModelChoiceField(queryset=Mealtypes.objects.filter(author=author))
class Meta:
model = Specificmeals
fields = ['author', 'meal_name', 'mealtype', 'fruit', 'meat', 'dairy']
widgets = {
'author': Select(),
'meal_name': TextInput(attrs={"style": "height:10em;" "width:60em;"}),
'fruit': CheckboxInput(attrs={"style": "margin-left:350px;"}),
'meat': CheckboxInput(attrs={"style": "margin-left:350px;"}),
'dairy': CheckboxInput(attrs={"style": "margin-left:350px;"})
}
不要忘記您必須author在表單中有一個欄位,因為它不能為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/346381.html
標籤:Python 姜戈 django-models django-forms
上一篇:更新視圖后重定向回原始帖子
下一篇:如何按版本Django過濾書籍?
