如何将两个模型合并为一种形式?

时间:2020-10-21 04:57:58

标签: python django django-models

是否可以将两个不同的模型合并为一个表单?如果是,那么请向我提供解决方案。 基本上,我想创建一个表单,在其中还可以添加图像,但是由于我想使其正常工作而无法正常工作。

models.py:

 class Mobile(models.Model):
      brand = models.CharField(max_length=30)
      price = models.IntegerField(default=1)
      color = models.CharField(max_length=30)
      screen_size = models.IntegerField(default=5)
      os = models.CharField(max_length=30, default='Samsung')

      def __unicode__(self):
          return self.brand


class MobileImage(models.Model):
     device = models.ForeignKey(Mobile, on_delete=models.CASCADE)
     image = models.ImageField(upload_to='media/images/')

     def __unicode__(self):
         return self.device

forms.py:

from django import forms
from .models import Mobile, Laptop, MobileImage


class AddMobileForm(forms.ModelForm):

    class Meta:
        model = Mobile
        fields = '__all__'

views.py:

def addmobile(request):
    if request.method == 'POST':
        mobileform = AddMobileForm(request.POST)
        if mobileform.is_valid():

           mobileform.save()
           return redirect('mobile')
    else:
        mobileform = AddMobileForm()

  context = {
    'mobile_form': mobileform
}
return render(request, 'device/mobile_form.html', context)

0 个答案:

没有答案