首页 > 解决方案 > Django 表单图像选择 - 小部件类型

问题描述

行。我想制作一个从模型 A 更改图像的应用程序,并将其另存为模型 B。在模板中的表单上,我希望选择可见图像。我该怎么做?

型号和形式A

模型

from django.db import models


class Photo(models.Model):
    photo = models.ImageField(blank=True, null=True)

形式

from django import forms
from .models import Photo


class Photoform(forms.ModelForm):
    photo = forms.ImageField(required=True)

    class Meta:
        model = Photo
        fields = ('photo',)

型号和形式 B

模型

from django.db import models


class Meme(models.Model):
    meme = models.ImageField(blank=True, null=True)

形式

from django import forms
from Uploader.models import Photo


class Memeform(forms.Form):
    meme = forms.ModelChoiceField(Photo.objects.all(), widget=forms.RadioSelect)

    class Meta:
        model = Photo
        fields = ('meme',)

模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method= "post" enctype="multipart/form-data">
        <p>
            <h2>Your image here</h2>
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Create</button>
        </p>
    </form>
</body>
</html>

现在我有小部件 RadioSelect,但我需要选择可见的图像。

标签: pythondjangodjango-modelsdjango-forms

解决方案


form.fields["photo"].queryset = Photo.objects.all()在您的意见中..您可以从这里参考更多.. http://www.wkoorts.com/wkblog/2009/08/10/pre-populate-django-modelform-with-specific-queryset/


推荐阅读