0

所以,我想知道是否有可能让 django modelform 访问超过 1 个 django 模型......我目前有 2 个与产品相关的模型,它们如下所示......我制作 2 个模型的原因是允许每个产品有多个图像

class Product(models.Model):
    title = models.CharField(max_length=255)
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    thumbnail = models.ImageField(upload_to='uploaded_products/', blank=True, null=True)
    description = models.TextField(max_length=255, null=True, blank=True)
    categories = models.ManyToManyField(Category,related_name='products', blank=True, help_text="Select One or More Categories that the product falls into, hold down ctrl to select mutiple categories")
    tags = models.ManyToManyField(Tag, blank=True)
    stock = models.PositiveIntegerField(default=1, blank=True)
    notes = models.TextField(null=True, blank=True)
    ownership = models.FileField(blank=True, null=True, upload_to='product_files', help_text='Optional : provide valid document/picture to proof ownership (presence of this document increases the reputation of your product).Note: Provided Document if invalid or incorrect can be invalidated after upload')
    verified = models.BooleanField(default=False, blank=True, null=True)
    uploader = models.ForeignKey(Account, on_delete=models.CASCADE, blank=True)
    serial_number = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        ordering = ['-updated']

    def __str__(self):
        return self.title

class Product_Image(models.Model):
    name = models.CharField(max_length=255, blank=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='uploaded_products/')
    default = models.BooleanField(default=False, blank=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.name:
            self.name = self.product.title
        super().save(*args, **kwargs)

现在我希望能够在模型表单中访问两个模型并进行适当的编辑..目前我尝试将第二个模型添加到模型元类属性中,它清楚地表明这是不可能的....如果访问 2 个模型不可能,我可以将什么可能的解决方案应用于我当前的模型结构以保持允许产品具有多个图像的能力。谢谢,因为我期待一个可行的解决方案。

4

1 回答 1

1

forms.py:

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = [add your field from this model here]

class ImagePostForm(ProductForm):
    #define the field your want here from Product_Image(using forms)
    image = forms.ImageField(label='Image',widget=forms.ClearableFileInput(attrs={'multiple': True}))
    class Meta(ProductForm.Meta):
        fields = ProductForm.Meta.fields + ['image',#add the field your want from Product_Image here]

Now inside your views.py you can just call ImagePostForm.you can do something like this
views.py

from .forms import ImagePostForm
from .models import Product,Product_Image
def your_view(request):
    if request.method=='POST':
            form=ImagePostForm(request.POST or None,request.FILES or None)
            files = request.FILES.getlist('image')
            if form.is_valid():
                post = form.save(commit=False)
                #add the things your want to add here after that you can save it  
                post.save()
                if files:
                        for f in files:
                            Product_Image.objects.create(product=post,image=f)
                redirect('the view here')
    else:
         form = ImagePostForm()
         return render(request,'your-template',{'form':form})
于 2021-09-29T16:05:48.947 回答