python - 如何在 Django 表单中添加 GenericRelation 字段

标签 python django django-1.10

我有以下错误:

django.core.exceptions.FieldError: 'pictures' cannot be specified for Building model form as it is a non-editable field

我有很多模型可以有很多图像。所以我使用了django的GenericRelation。但是当我在 forms.py 中添加“图片”字段时。我收到错误

表单.py

class BuildingForm(ModelForm):
    class Meta:
        model = Building
        fields = ['landlord', 'address', 'pictures']

模型.py

from stdimage.models import StdImageField

class Image(TimeStampedModel, models.Model):
    picture = StdImageField(upload_to='pictures/%Y/%m/%d',
                            verbose_name="pics", null = True, blank = True, variations={
        'large': (600, 400),
        'thumbnail': (250, 250, True),
        'medium': (300, 200),
    }, default='default.jpg')
    # Generic Foreign Key
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()


class Building(TimeStampedModel, models.Model):
    landlord = models.ForeignKey(
                settings.AUTH_USER_MODEL,
                related_name='building_manager')
    address = models.CharField(max_length=50, blank=False)
    pictures = GenericRelation(Image, null = True, blank = True,
        related_query_name='dwelling_picture', verbose_name=_('Screenshots'))

View .py

class BuildingCreateView(SuccessMessageMixin, CreateView):
    form_class = BuildingForm
    template_name = "parking/building/building_form.html"
    success_message = 'Successfully Added a Post entry'
    success_url = reverse_lazy('parkers:building_list')

    def form_valid(self, form):
        self.object = form.save(commit=True)
        #self.object.author = self.request.user
        return super(BuildingCreateView, self).form_valid(form)

parking_building_new = login_required(BuildingCreateView.as_view())

表单.html

<div class="container">
    <div class="row">
        <div class="col-lg-10 col-lg-1-offset">
            <form action="." method="post" enctype="multipart/form-data">
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" value="Submit" />
            </form>

        </div>
    </div>
</div>

跟踪

 File "/home/laptopvm/Documents/Github/django_project_tutorial_genericrelation_key/parking/urls.py", line 4, in <module>
    from parking.views import user_profile_views
  File "/home/laptopvm/Documents/Github/django_project_tutorial_genericrelation_key/parking/views/user_profile_views.py", line 26, in <module>
    from parking.forms  import UserProfileForm
  File "/home/laptopvm/Documents/Github/django_project_tutorial_genericrelation_key/parking/forms.py", line 7, in <module>
    class BuildingForm(ModelForm):
  File "/home/laptopvm/anaconda3/lib/python3.6/site-packages/django/forms/models.py", line 266, in __new__
    apply_limit_choices_to=False,
  File "/home/laptopvm/anaconda3/lib/python3.6/site-packages/django/forms/models.py", line 159, in fields_for_model
    f.name, model.__name__)
django.core.exceptions.FieldError: 'pictures' cannot be specified for Building model form as it is a non-editable field

最佳答案

GenericForeignKeys 不适合与 ModelForms 一起使用。它们不可故意编辑。您也不能对它们使用filter() 或exclusion()。您可以引用文档以获取更多信息:

https://docs.djangoproject.com/en/2.1/ref/contrib/contenttypes/#generic-relations

关于python - 如何在 Django 表单中添加 GenericRelation 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910847/

相关文章:

Django:提交表单时,自动填充字段

python - 在 python 中绘制泊松分布图

python - 将用户定义的函数作为 native 调用 | Python

python - 虚假导入错误(模块导入子模块?)

python - Django - 如何在一个 View 中保存多个对象

python - 不要国际化/翻译 URL

python - 将标签与过滤器结合起来

python - Django Rest 框架 - 如果表包含响应中的数据,则显示服务器错误 (500)

python - 用 BeautifulSoup 拆分一个元素

python - 找到在 Maya 中创建的最后一个窗口?