如何从一个模型中获取数据并以下拉列表形式显示以将其存储在django中的另一个模型中

时间:2019-05-22 06:14:24

标签: django django-models django-forms

我有3个模型,即类别,品牌,产品。我必须在产品表格中包括类别和品牌才能在下拉菜单中显示它,并且应该在产品表中分配选择的值。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

正如您所说,您有三个模型。类别,品牌,产品。

models.py

class Category(models.Model):
    #
    # Your logic here
    #

class Brand(models.Model):
    #
    # Your logic here
    #

class Products(models.Model):
    #
    # Your logic here
    #

现在基于模型(使用ModelForm)或仅使用Form类生成表单。

forms.py

class CategoryModelForm(forms.ModelForm):

    class Meta:
        model = Category
        fields = '__all__' # for example

class BrandForm(forms.Form):

    class Meta:
        model = Brand
        fields = '__all__' # for example

views.py

def index(request):
    if request.method == 'POST':
        cf = CategoryForm(data=request.POST)
        bf = BrandForm(data=request.POST)
        if cf.is_valid() and bf.is_valid(): # validate both form together
            # cf.cleaned_data and bf.cleaned_data returns validated data.
            print('CategoryForm valid data => ', cf.cleaned_data)
            print('BrandForm valid data => ', bf.cleaned_data)
            Products.objects.create(field1=cf.cleaned_data['some_field'], field2=bf.cleaned_data['some_field']) # you should implement your own logic. Performs database insert query.
            return JsonResponse({'status_message': 'Successfully updated Products table'})
    else:
        cf = CategoryForm()
        bf = BrandForm()
    return render(request, 'index.html', {'cf': cf, 'bf': bf})

index.html

<form accept="" method="POST">
    {% csrf_token %}
    {{ cf.as_p }} <br />
    {{ bf.as_p }}
    <input type="submit" value="click" />
</form>

我希望它将对您有帮助!