【问题标题】:Django ModelForm in Modal on Home Page主页上模态中的 Django ModelForm
【发布时间】:2019-05-24 21:12:32
【问题描述】:

我有一个表单,它在 Django 应用程序中的自己的模板页面“build-project-custom.html”上呈现。我正在尝试将表单重复为主页上的弹出模式。我不断收到错误:

参数“field”应该包含一个有效的 Django BoundField。

我认为我不太了解 ModelForm 在视图中的工作方式或它们如何填充到另一个基于类的视图中。我基本上希望用户能够在主页上的模式上提交此表单。非常感谢您的帮助。我对 Python 和 Django 还很陌生,因此非常感谢您提供简单的解释。

buildproject/models.py

class CustomProjectBuildRequest(models.Model):
CUSTOM_PROJECT_CONTACT_METHOD = (
    ('Email', 'Email'),
    ('Call', 'Call'),
    ('Text', 'Text'),
)
first_name = models.CharField(max_length=100, null=False, verbose_name='First Name')
last_name = models.CharField(max_length=100, null=False, verbose_name='Last Name')
email = models.EmailField(max_length=255, unique=False, verbose_name='Email')
phone_number = PhoneNumberField(null=False, blank=False, verbose_name='Phone')
created_timestamp = models.DateTimeField(auto_now_add=True, verbose_name='Requested')
updated_timestamp = models.DateTimeField(auto_now=True, verbose_name='Updated')
project_name = models.CharField(max_length=100, verbose_name='Project Name')
project_description = models.TextField(null=False, verbose_name='Description')
preferred_contact_method = models.CharField(max_length=512, choices=CUSTOM_PROJECT_CONTACT_METHOD,
                                            verbose_name='Preferred Contact Method')

# Admin database comments for each project request created
customer_contacted = models.DateTimeField(null=True, blank=True, verbose_name='Customer Contacted')
customer_comments = models.TextField(max_length=512, null=True, blank=True, verbose_name='Admin Comments')

buildproject/forms.py

class CustomProjectBuildRequest(forms.ModelForm):
class Meta:
    model = CustomProjectBuildRequest
    fields = ['first_name', 'last_name', 'email', 'phone_number', 'project_name', 'project_description',
              'preferred_contact_method']

class PMPIndex(ListView):
template_name = 'pmp/index.html'
model = Post

buildproject/views.py

def custom_project_build_request(request):
if request.method != 'POST':
    form = CustomProjectBuildRequest()
elif request.method == 'POST':
    form = CustomProjectBuildRequest(data=request.POST)
    if form.is_valid():
        form.save()
        messages.success(request, "Form successfully submitted")

return render(request, 'build-project-custom.html', {
    'form': form,
})

主页 Views.py

class PMPIndex(ListView):
template_name = 'pmp/index.html'
model = Post

def custom_project_build_request(request):
    if request.method == 'POST':
        form = CustomProjectBuildRequest(data=request.POST)
        if form.is_valid():
            form.save()
    else:
        form = CustomProjectBuildRequest()
    return render(request, 'build-project-custom.html', {'form': form}))

主页模式

<div class="modal fade" id="request-custom-project-modal" tabindex="-1" role="dialog"
 aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-
            {% include 'build-project-custom.html' %}
  </div>
  <div class=" modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
</div>

【问题讨论】:

  • 为什么你的模型和表单有相同的名称CustomProjectBuildRequest
  • 我想我应该把它改成 CustomProjectBuildRequestForm
  • 您的代码中有错误。它们是在复制和粘贴过程中发生的吗?
  • 我不知道。

标签: python django forms bootstrap-modal modelform


【解决方案1】:

我必须将 FormView 添加到基于类的视图中。

class PMPIndex(ListView, FormView):
template_name = 'pmp/index.html'
model = Post

form_class = CustomProjectBuildRequestForm
success_url = reverse_lazy('home')

def form_valid(self, form):
    form.save()
    return super(PMPIndex, self).form_valid(form)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['posts'] = Post.objects.all()
    context['lastThreePosts'] = Post.objects.order_by('-posted')[:3]
    return context

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.object = None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2013-06-24
    • 2013-11-06
    • 2011-04-14
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    相关资源
    最近更新 更多