答案 0 :(得分:0)
正如您所说,您有三个模型。类别,品牌,产品。
class Category(models.Model):
#
# Your logic here
#
class Brand(models.Model):
#
# Your logic here
#
class Products(models.Model):
#
# Your logic here
#
现在基于模型(使用ModelForm
)或仅使用Form
类生成表单。
class CategoryModelForm(forms.ModelForm):
class Meta:
model = Category
fields = '__all__' # for example
class BrandForm(forms.Form):
class Meta:
model = Brand
fields = '__all__' # for example
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})
<form accept="" method="POST">
{% csrf_token %}
{{ cf.as_p }} <br />
{{ bf.as_p }}
<input type="submit" value="click" />
</form>
我希望它将对您有帮助!