Crispy_forms.Exceptions.CrispyError: |as_crispy_field 传递了无效或不存在的字段 - models.ForeignKey

发布于 2025-01-11 20:44:49 字数 3774 浏览 2 评论 0原文

我正在尝试为现有模型创建前端数据输入页面。但是,当单击该链接时,我收到一个错误:

crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field

需要明确的是,从 Django Admin 添加数据完全没有问题。

在这里查看了一些已回答的问题后,确实强调了我认为可能存在问题的地方,但它断章取义,没有提供太多解释。

我正在尝试为与外键对应的用户创建一个前端输入表单。

models.py

class NewHandoff(models.Model):
    handoff_pk = models.AutoField(primary_key=True)
    handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date")
    shift1_pri = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Primary")
    shift1_sec = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Secondary")

    def __str__(self):
        return f"{self.handoff_date}"
    
    class Meta:
        verbose_name_plural = 'Handoffs'

# New Handoff Form
class NewHandoffForm(forms.ModelForm):
    class Meta:
        model = NewHandoff
        fields = ['shift1_pri','shift1_sec']

views.py

from django.shortcuts import redirect, render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponse
from django.contrib import messages
from .models import AttentionForm,  NewHandoffForm

# Handoff View Page
class NewHandoffView(LoginRequiredMixin,View):
    def get(self, request):
        greeting = {}
        greeting['heading'] = "New Handoff"
        greeting['pageview'] = "Handoff"
        return render (request,'handoff/handoff-new.html')

    def post(self, request):
        if request.method == "POST":
            if "add-new-handoff-button" in request.POST:
                create_new_handoff_form = NewHandoffForm(request.POST)
                create_new_handoff_form.save()
                return redirect("/handoff/handoff-create")

handoff-new.html

{% extends 'partials/base.html' %}
{% load static %}
{% load humanize %}
{% load crispy_forms_tags %}

{% block extra_css %}
    <link href="{% static 'libs/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' %}" rel="stylesheet">
{% endblock %}

{% block contents %}
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <!-- New Form -->
                    <form method="POST">
                        {% csrf_token %}
                        <div class="row">
                            <div class="row-fluid pb-1">
                                <!-- Field 1 -->
                                <div class="mb-3">
                                    {{ form.shift1_pri|as_crispy_field }}
                                </div>
                                <!-- End of Field 1 -->
                            </div>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            <button type="submit" class="btn btn-primary waves-effect waves-light" name="add-new-handoff-button">Create New Handoff</button>
                        </div>
                    </form>
                    <!-- End of New Form -->
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block extra_javascript %}
{% endblock %}

有人在另一篇文章中提到表单应与声明的表单名称相关联 { { form.shift1_mod|as_crispy_field }} 所以它实际上应该是 {{ create_new_handoff_form.shift1_mod|as_crispy_field }} 但我尝试改变这个并且仍然遇到同样的问题,另外,尽管表单的名称是attention_form,但另一个模型表单仅适用于表单即可正常工作。

有谁有任何想法或可以指出我正确的方向吗? :)

I'm trying to create a frontend data entry page for an existing model. However, when clicking the link, I get an error:

crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field

Just to be clear, adding the data from Django Admin works with no issues at all.

Having looked through a number of answered questions here, one did highlight what I believe could be problem, but it was out of context and did not provide much of an explanation.

I am trying to create a frontend entry form for users that corresponds with a foreign key.

models.py

class NewHandoff(models.Model):
    handoff_pk = models.AutoField(primary_key=True)
    handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date")
    shift1_pri = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Primary")
    shift1_sec = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Secondary")

    def __str__(self):
        return f"{self.handoff_date}"
    
    class Meta:
        verbose_name_plural = 'Handoffs'

# New Handoff Form
class NewHandoffForm(forms.ModelForm):
    class Meta:
        model = NewHandoff
        fields = ['shift1_pri','shift1_sec']

views.py

from django.shortcuts import redirect, render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponse
from django.contrib import messages
from .models import AttentionForm,  NewHandoffForm

# Handoff View Page
class NewHandoffView(LoginRequiredMixin,View):
    def get(self, request):
        greeting = {}
        greeting['heading'] = "New Handoff"
        greeting['pageview'] = "Handoff"
        return render (request,'handoff/handoff-new.html')

    def post(self, request):
        if request.method == "POST":
            if "add-new-handoff-button" in request.POST:
                create_new_handoff_form = NewHandoffForm(request.POST)
                create_new_handoff_form.save()
                return redirect("/handoff/handoff-create")

handoff-new.html

{% extends 'partials/base.html' %}
{% load static %}
{% load humanize %}
{% load crispy_forms_tags %}

{% block extra_css %}
    <link href="{% static 'libs/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' %}" rel="stylesheet">
{% endblock %}

{% block contents %}
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <!-- New Form -->
                    <form method="POST">
                        {% csrf_token %}
                        <div class="row">
                            <div class="row-fluid pb-1">
                                <!-- Field 1 -->
                                <div class="mb-3">
                                    {{ form.shift1_pri|as_crispy_field }}
                                </div>
                                <!-- End of Field 1 -->
                            </div>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            <button type="submit" class="btn btn-primary waves-effect waves-light" name="add-new-handoff-button">Create New Handoff</button>
                        </div>
                    </form>
                    <!-- End of New Form -->
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block extra_javascript %}
{% endblock %}

Someone mentioned in another post that forms should correlate with the declared form name {{ form.shift1_mod|as_crispy_field }} so it should actually be {{ create_new_handoff_form.shift1_mod|as_crispy_field }} but I have tried changing this and still get the same problem, plus, another model form works fine with just form despite the name of the form being attention_form.

Does anyone have any idea or can point me in the right direction? :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满意归宿 2025-01-18 20:44:49

您没有通过模板中的上下文传递表单。当您继承 View 时,请在 get() 中添加以下行,然后在 post() 方法中适当添加以下行:

form = NewHandoffForm()

# and then change return
return render(request,'handoff/handoff-new.html', {'form': form })

此外,在 get 函数中的 render 之后有一个空格。我希望这是这里的拼写错误,但不是您的代码中的拼写错误。

You are not passing the form through the context in the template. As you are inheriting View, Add the following line in the get() and afterwards in the post() method appropriately:

form = NewHandoffForm()

# and then change return
return render(request,'handoff/handoff-new.html', {'form': form })

Also, you have a space after render in the get function. I hope this is a typo here, but not in your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文