簡體   English   中英

Django - 如何使用登錄用戶過濾的另一個模型中的字段填充模型選擇字段中的選項

[英]Django - How to populate choices in a modelchoicefield with a field from another model filtered by logged in user

我正在嘗試使用 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 模型中查詢膳食類型,但我不斷收到屬性錯誤(對象沒有屬性..)

我做錯了什么,我該如何解決?

首先,將以下內容添加到您的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字段,因為它不能為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM